Feb 17, 2009

WPF Validation

Up until recently the mechanisms that Windows Presentation Foundation provided to implement validation were quite unsatisfying.

Starting with .NET 3.0 there was a way to do simple field validation:

<Binding Path="SemanticId" UpdateSourceTrigger="PropertyChanged">

    <Binding.ValidationRules>

        <XyValidationRule/>

    </Binding.ValidationRules>

</Binding>



For most applications this is not enough, however. Usually several fields from an entity are bound to several elements on a form and they have to be validated as a whole to be consistent.

A new approach came with .NET 3.5 where an POCO entity could implement an interface to be used by :


public class Contact : IDataErrorInfo



What I don't like is messing up my entities with validation code. I would prefer a separated (aspect-oriented? and) configurable way.

Rather unnoticed yet another approach came with 3.5 SP1, where you can group several element bindings to one or more entities and define validation rules for this named group:

<Grid.BindingGroup>

    <BindingGroup Name="TrainValidationGroup">

        <BindingGroup.ValidationRules>

            <my:TrainValidationRule ValidationStep="CommittedValue"/>

        </BindingGroup.ValidationRules>

    </BindingGroup>

</Grid.BindingGroup>



It is used in each binding

<TextBox Text="{Binding Path=SemanticId, BindingGroupName=TrainValidationGroup, ValidatesOnDataErrors=true}"/>



Not to forget to explicitely calling

RootElement.BindingGroup.CommitEdit();



Check out the excellent posts I had as source:
MSDN blog
Vincent Sibal

No comments:

Post a Comment