Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

3. Advanced Data Binding > Validating data-bound input

Validating data-bound input

Validating data-bound input Applies to Silverlight 3, 4 and 5 Validation of your data is a requirement for almost every application. By using validation, you make sure that no invalid data is (eventually) persisted in your data store. When you don't implement validation, there is a risk that a user will input wrongly-formatted or plain incorrect data on the screen and even persist this data in your data store. This is something you should definitely avoid. In this recipe, we'll learn about implementing client-side validation on the bound fields in the UI. Getting ready To get ready for this recipe, you can either use the code from one of the previous recipes or use the provided starter solution in the Chapter03/SilverlightBanking_Validation_Starter folder in the code bundle available on the Packt website. The complete solution for this recipe can be found in the Chapter03/SilverlightBanking_Validation_Completed folder. How to do it... We're going to add validation logic to the OwnerDetailsEdit screen you created by following all the steps of the Using the different modes of data binding to allow persisting data recipe in the previous chapter (Alternatively, you can use the starter solution.). To achieve this, we'll carry out the following steps: Open the solution that you created in the Using the different modes of data binding to allow persisting data recipe (or the starter solution) and locate the OwnerDetailsEdit.xaml file. In this XAML file, locate and change the LastNameValueTextBlock and the BirthDateValueTextBlock by adding NotifyOnValidationError=true and ValidatesOnExceptions=true to the Binding syntax. This is shown in the following code: <TextBox x:Name="LastNameValueTextBlock" Grid.Row="3" Grid.Column="1" Margin="2" Text="{Binding LastName, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" > </TextBox> <TextBox x:Name="BirthDateValueTextBlock" Grid.Row="9" Grid.Column="1" Margin="2" Text="{Binding BirthDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" > </TextBox> Add a handler to the surrounding Grid, that is, OwnerDetailsGrid. This is shown in the following code: <Grid x:Name="OwnerDetailsGrid" BindingValidationError="OwnerDetailsGrid_ BindingValidationError"> Add the following C# code to OwnerDetailsEdit.xaml.cs. This implements the handler we defined in the previous step. private void OwnerDetailsGrid_BindingValidationError(object sender, ValidationErrorEventArgs e) { if (e.Action == ValidationErrorEventAction.Added) OwnerDetailsGrid.Background = new SolidColorBrush(Color.FromArgb(25, 255, 0, 0)); if (e.Action == ValidationErrorEventAction.Removed) OwnerDetailsGrid.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); } Locate the Owner.cs file, which represents the type of DataContext of the OwnerDetailsEdit control. Add the following code to the set accessor of LastName to make sure that a validation error is thrown when needed. set { if (lastName != value) { if (value.Length > 20) { throw new Exception("Length must be <= 20"); } else { lastName = value; OnPropertyChanged("LastName"); } } } We can now build and run the solution. When invalid data is inputted (a string that's too long for the Last name field or a value that isn't in a correct format for the Birthdate field), a validation error will occur. The result can be observed in the following screenshot: How it works... Silverlight automatically reports a validation error in a few cases. These include when type conversion fails on binding, when an exception is thrown in a property's set accessor, or when a value doesn't correspond to the applied validation attribute (more on this can be found in the next recipe, Validating data input using attributes). In our example, we're throwing an exception in the property's set accessor. This means Silverlight will report the error. Next to that, Silverlight will also report an error when you try to input a value that doesn't correspond with the underlying type (you can try to input an invalid date value in the Birthdate field) If you look at the Binding syntax in XAML, you'll see that we've added a few things, ValidatesOnExceptions and NotifyOnValidationError are set to true. Setting ValidatesOnExceptions to true makes sure that Silverlight will provide visual feedback for the validation errors it reports. Setting NotifyOnValidationError to true makes sure that the binding engine raises the BindingValidationError event when a validation error occurs. In the parent grid, this BindingValidationError event gets handled. We've the written code that will change the background color of the complete box if an error occurs (this is optional). Client-side validation is easily implemented by bringing these three principles together in the example you've just created. There's more... Along with reporting a validation error when type conversion fails on binding or when an exception is thrown in a property's set accessor, Silverlight also reports an error when a value doesn't correspond to the applied validation attribute. More on this can be found in the next recipe. As you've noticed while running the solution we've created, Silverlight has a default style for showing the validation error. This can, of course, be customized by changing the control's default ControlTemplate. More information on customizing templates can be found in the Using templates to customize the way data is shown by controls recipe. And last but not least, we can provide more detailed validation reporting by using the ValidationSummary control. This ValidationSummary control will automatically receive the BindingValidationError events of its parent container. On each BindingValidationError, the ValidationSummary receives a newly-created ValidationSummaryItem (added to ValidationSummary.Errors) with corresponding Message, MessageHeader, ItemType, and Context properties. Next to that, a new ValidationSummaryItemSource is created (and added to ValidationSummaryItem.Sources) with corresponding Control and PropertyName properties. To use a ValidationSummary in the example created in this recipe, we have to add a reference to System.Windows.Controls.Data.Input in the Silverlight project and add the following code to the OwnerDetailsEdit control: xmlns:datainput="clr-namespace:System.Windows.Controls; assembly=System.Windows.Controls.Data.Input" This will make sure that we can use ValidationSummary. Next, we'll have to locate the OK button and add a ValidationSummary control. This is shown in the following code: <datainput:ValidationSummary Grid.Row="1" Margin="2,5,2,5"> </datainput:ValidationSummary> <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="2" /> When we run our solution and input invalid data, a validation summary will be shown. This can be seen in the following screenshot: See also If you want to learn more about validation, you might want to take a look at the next two recipes, Validating data input using attributes and Validating using IDataErrorInfo and INotifyDataErrorInfo. To learn more about two-way data binding, have a look at the Using the different modes of data binding to allow persisting data recipe in Chapter 2,An Introduction to Data Binding.

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint