(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .
        Login with Facebook

Tip: How to validate values against certain rules when using binding?

(1 votes)
Denislav Savkov
>
Denislav Savkov
Joined Feb 11, 2008
Articles:   14
Comments:   6
More Articles
0 comments   /   posted on Sep 17, 2008
Categories:   Data Binding

Typically validation occurs when in a two-way binding the business object (source property) is updated with data from the user input (target property). During the update there are two places where validation occurs.

  1. First, the binding engine uses a implementation of IValueConverter to convert the data from one type to the other. Usually this converter has some validation. Unfortunately, Silverlight doesn't provide a way for custom validation for binding, like in WPF. There is no ValidationRule class that is used in WPF to provide the custom rule for the validation.
  2. Second, the setter of the property being updated may contain validation.

This means that if you want custom validation you have to write your own type converters or to place the validation inside the setters of your business object. In case the validation fails, an exception is thrown in a setter or in a converter , then a BindingValidationError event is raised (it is member of System.Windows.Controls.FrameworkElement). This makes it easy for you to prompt the user to enter correct data. BindingValidationError can be raised only when both NotifyOnValidationError and ValidatesOnExceptions are true. Setting ValidatesOnExceptions to true tells the binding engine to report validation exceptions and setting NotifyOnValidationError to true tells the binding engine to raise the BindingValidationError event when a validation error occurs. This, combined with the TwoWay mode of binding, gives us the following:

XAML

<TextBox x:Name="bindingTarget" Text="{Binding Path=Age,
                                               Source={StaticResource person},
                                               Mode=TwoWay,
                                               NotifyOnValidationError=true,
                                               ValidatesOnExceptions=true}" />. 
C#
bindingTarget.BindingValidationError +=
             new EventHandler<ValidationErrorEventArgs>( bindingTarget_BindingValidationError );

Here Age is a property of the object person.

Strangely BindingValidationError won’t raise if you use custom type converters in your binding. Check out our demo and download the source.

That's it!


Subscribe

Comments

No comments

Add Comment

Login to comment:
  *      *       
Login with Facebook