Home > View Post

New in WPF 3.5: 1. Neater syntax for core Validation Rules

Over the next few posts I want to examine some of the changes introduced to WPF in version 3.5 of the .NET framework. There isn't a lot of additions, but some of the changes are worth knowing.

In Reason 10 of the series:10 reasons to consider WPF for your next desktop application we looked at Validation.

Specifically, we took a basic TextBox with a binding to a property...

<TextBox Text="{Binding Name}" />

... and we added an ExceptionValidationRule to the binding's list of ValidationRules. Which looked like this:

<TextBox Grid.Row="0" Grid.Column="1" Margin="3">
    <TextBox.Text>
        <Binding Path="Name">
            <Binding.ValidationRules>
                <ExceptionValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

Nice, but one thing I hate about this is the sudden verbosity that hits your once elegant binding syntax - especially when you consider this is going to be very common and necessary on many, if not most, of you bindings. Fortunately, the chaps at WPF HQ have recognised this and added two properties to the binding class.

  • ValidatesOnExceptions : bool
  • ValidatesOnDataErrors : bool
If we set ValidatesOnExceptions to true, then the ExceptionValidationRule is automatically added to the Binding and because this property isn't a collection we can set the property in a markup extension. Like so:

<TextBox Text="{Binding Name, ValidatesOnExceptions=true}" />

I'm sure you'll agree that that's much neater :)

So what's this ValidatesOnDataErrors thing all about then?

Stay tuned for the next post where we'll look at another new feature for WPF in .NET 3.5 and all will be explained.

Tags: WPF

 
Josh Post By Josh Twist
9:48 AM
18 Jan 2008

» Next Post: New in WPF 3.5: 2. Support for IDataErrorInfo
« Previous Post: Sharing types between the client and the server in WCF

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.