WPF 3.5 Data Validation – Shorter Syntax

One great new feature in the .NET 3.5 Framework is, WPF now supports the IDataErrorInfo interface when data binding.  You can read an article posted by the SDK Team here Data Validation In 3.5.

I read the article and found that their example syntax looked long hand to me so I changed it to be much shorter.

SDK Example Syntax

Nested <Binding> within the <TextBox> control.

<TextBox x:Name="txtLastName">
    <Binding Path="LastName" UpdateSourceTrigger="LostFocus"
             Mode="TwoWay" ValidatesOnDataErrors="True"/>
</TextBox>

Shorter Syntax

<TextBox> control on a single line of XAML. (on two lines here to fit in lmited space)

<TextBox x:Name="txtFirstName" Text="{Binding Path=FirstName, UpdateSourceTrigger=LostFocus,
         Mode=TwoWay, ValidatesOnDataErrors=True}" />

I like this shorter syntax since it will fit in one line of XAML code and shortens the vertical length of my XAML files.  You can also add any required converters if required to this same syntax.

For those who prefer the longer syntax, go for it.  This is WPF, you can have it your way!

Just a grain of sand on the worlds beaches.

3 Responses to “WPF 3.5 Data Validation – Shorter Syntax”

  1. » Daily Bits - February 14, 2008 Alvin Ashcraft’s Daily Geek Bits: Daily links, development, gadgets and raising rugrats. Says:

    [...] WPF 3.5 Data Validation – Shorter Syntax (Karl Shifflett) [...]

  2. loicberthollet Says:

    Hello Karl,

    A little question: When I bind a classical Textbox to an Int32 ‘Age’ property, the shorter form seems very good for IDataErrorInfo; but when the textbox contains a non-numerical value (ie ‘hello’), a binding error is raised and swallowed by WPF…
    So, I to use the long syntax, just for adding “”.

    To your mind, is it possible to use the short syntax in that case ?
    I try many syntax and have no more ideas!

    Cheers,
    Loïc

  3. Karl Shifflett Says:

    Loïc,

    Have a look at the code I post here: http://karlshifflett.wordpress.com/2008/05/16/wpf-multi-tier-business-application-track-code-camp-source-code/ It provides a full solution for the exact situation you are bringing up.

    I also posted this: http://karlshifflett.wordpress.com/2008/04/03/wpf-sample-series-handling-and-reporting-wpf-data-binding-validation-errors-and-exceptions/ It goes into depth about exceptions in the data binding pipeline.

    Cheers,

    Karl

Leave a Reply

You must be logged in to post a comment.