Colin Eberhardt's Technology Adventures

BindingGroups for Total View Validation

January 26th, 2009

Over the weekend Sacha published a new article on codeproject, Total View Validation (does Sacha ever sleep?). This article addresses some of the perceived problems with the WPF binding framework, firstly, that the standard solution of using the ValidatesOnDataErrors property forces you to place validation logic into your bound business objects, and secondly, that there is no way to perform validation across multiple objects. His solution to both these problems was to construct a view model which contains the validation rules and applies them to all the objects within the form. A collection of validation failures are associated with the view model. These can either be rendered in their entirety or each control within the view can render errors relating to their context.

This blog post describes how BindingGroups can be used to address the problem of applying validation rules to multiple objects.

BindingGroups were introduced as part of .NET 3.5 SP1, Vincent Sibal provides a good introduction to this new features on his blog. I have previously blogged on the subject of BindingGroups, where I demonstrated how they can be used to provide improved error messages when type conversion fails during the binding process.

In this post I will take the application from Sacha’s article and modify it to use BindingGroups. The following is a screenshot of the application:

form

The form displays the details of two People (two instances of the Person class). The user inputs data using the above controls then clicks the Validate button to run all the Form’s validation rules. Most of the validation rules relate to a single property of the bound object, e.g. FullName cannot be empty. However there is one trick validation rule:

“If Person 1′s age is less than 18, Person 2′s age cannot be zero”

This rule cannot be evaluated by assocaiting it with the Age property of either person. It requires access to both Person instances, hence it really belongs at the scope of the form itself. This is where BindingGroups come in …

The XAML below shows our form which consists of a pair of StackPanels that contain fields bound to our Person instances by setting their DataContext properties in the code-behind. The ‘root’ element of the Window contains our BindingGroup.

<StackPanel Name="RootElement" Orientation="Vertical">
    <!-- the binding group for this form -->
    <StackPanel.BindingGroup>
        <BindingGroup Name="FormBindingGroup">
            <BindingGroup.ValidationRules>
                <local:PersonValidationRule
                            ValidationStep="CommittedValue"/>
            </BindingGroup.ValidationRules>
        </BindingGroup>
    </StackPanel.BindingGroup>
 
    <Border>
 
        <StackPanel Orientation="Vertical">
 
            <!-- Person One fields -->
            <StackPanel Name="personOnePanel" Orientation="Vertical">
                <Label Content="Person1"/>
 
                <!-- FirstName Property-->
                <StackPanel Orientation="Horizontal" >
                    <Label Content="FirstName" />
                    <TextBox Text="{Binding Path=FirstName, 
                                           BindingGroupName=FormBindingGroup,
                                           ValidatesOnDataErrors=true}" />                            
                </StackPanel>
 
                <!-- LastName Property-->
                ...
            </StackPanel>
 
            <!-- Person Twofields -->
            <StackPanel Name="personTwoPanel"  Orientation="Vertical">
                <Label Content="Person2"/>
 
                <!-- FirstName Property-->
                <StackPanel Orientation="Horizontal" >
                    <Label Content="FirstName" />
                    <TextBox Text="{Binding Path=FirstName, 
                                           BindingGroupName=FormBindingGroup,
                                           ValidatesOnDataErrors=true}" />                            
                </StackPanel>
 
                <!-- LastName Property-->
                ...
            </StackPanel>
 
        </StackPanel>
 
    </Border>
 
    <StackPanel Orientation="Vertical">
 
        <Button x:Name="btnValidate" Content="Validate" Margin="5"  />
 
    </StackPanel>
</StackPanel>

Rules associated with a BindingGroup have access to both their associated binding expressions, and the source objects used by these bindings. A BindingGroup becomes associated with a collection of binding expressions if it shares the same DataContext. However, in the above example we have a pair of objects, therefore we cannot share a DataContext across all the elements in our XAML (this is not strictly true, we could construct a view model for this purpose, however I really want to illustrate one of the other features of BindingGroups). BindingGroups can also be explicitly associated with a Binding via its BindingGroupName property.

So just what exactly can we do with our BindingGroup? It is possible to execute this rule at various different steps of the binding process, for example, it is possible to evaluate the rule before type conversion has occurred. In this instance, we are only interested in the converted value, hence the ValidationStep property is set to CommittedValue. The rule itself is very simple:

public class PersonValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        BindingGroup bindingGroup = (BindingGroup)value;
 
        // extract the two bound Person instances.
        Person personOne = bindingGroup.Items[0] as Person;
        Person personTwo = bindingGroup.Items[1] as Person;
 
        if (personTwo.Age==0 && personOne.Age<18)
        {
            return new ValidationResult(false,
                     "Person 2 Age can't be zero if Person1 Age < 18");
        }           
 
        return ValidationResult.ValidResult;
    }
}

We simply retrieve both Person instances, apply our rule raising an error if our condition is not met. Any validation errors returned by the BindingGroup become associated with the Validation.Errors attached property of the element which the BindingGroup is associated with. Therefore they can be accessed and styled in the ‘standard’ way, for example:

<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip"
                Value="{Binding RelativeSource={RelativeSource Self}, 
                       Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
    </Style.Triggers>
</Style>

See the excellent article Validation in WPF for details.

However, BindingGroups offer one further advantage, validation errors from the associated binding expressions are also placed in the Validation.Errors collection, therefore we can output all the validation errors for our form by binding to this property as follows:

<ItemsControl ItemsSource="{Binding Path=(Validation.Errors), ElementName=RootElement}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Label Foreground="Red" Content="{Binding Path=ErrorContent}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The following screenshot shows the form where multiple validation errors are present:

errors

Conclusions

So … which approach is better? BindingGroups or Sacha’s ViewModel technique?

Personally, I don’t think there is one best approach – and this blog post is certainly not an attack on Sacha’s article, which presents an elegant solution. My intention is to simply show that it is possible to perform validation on multiple objects at a ‘wider’ scope with the standard WPF framework.

To quote Mike Hillberg, the Poo is Optional.

A sample project with the code from this post is available for download: bindinggroupsglobalvalidation.zip.

Regards, Colin E.

WPF DataGrid – Committing changes cell-by-cell

January 21st, 2009

In my recent codeproject article on the DataGrid I described a number of techniques for handling the updates to DataTables which are bound to the grid. These examples all worked on the assumption that you want to keep your database synchronised with the DataGrid, with changes being committed on a row-by-row basis, i.e. when the user finishes editing a row the changes are written to the database. The WPF DataGrid operates in a row-oriented manner making this a relatively straightforward scenario to implement.

However, what if you want to commit changes on a cell-by-cell basis? Firstly, lets have a look at the problem in a bit more detail. The following code displays a DataGrid, together with a ‘details’ view. Note that IsSynchronizedWithCurrentItem is set to true so that the details view and currently selected item within the grid will remain synchronised:

<DockPanel DataContext="{Binding Source={StaticResource PersonData}}">
 
  <Border DockPanel.Dock="Bottom" Padding="10">
    <Grid x:Name="RootElement">
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="1.8*"/>
      </Grid.ColumnDefinitions>
 
      <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
      </Grid.RowDefinitions>
 
      <Label Content="Forename:"/>
      <TextBox Grid.Column="1" Text="{Binding Forename}"/>
 
      <Label Grid.Row="1" Content="Surname:"/>
      <TextBox  Grid.Row="1" Grid.Column="1" Text="{Binding Surname}"/>
 
      <Label Grid.Row="2"  Content="Age:"/>
      <TextBox Grid.Row="2"   Grid.Column="1" Text="{Binding Age}"/>
    </Grid>
  </Border>
 
  <dg:DataGrid ItemsSource="{Binding}" Name="dataGrid"
         IsSynchronizedWithCurrentItem="true"/>
</DockPanel>

The ‘PersonData’ in this case is a DataTable that is constructed in the code-behind.

Now, with this example, if you make changes to a persons surname, then click on the age cell and make changes there, the changes in surname are not reflected in the details view below:

rownotcommitted

In the above example the user has entered the surname “Blunt” and has moved onto the age cell, however the changes are not reflected in the details view below.

Why is this?

The reason is that when you bind to a DataTable, you are actually binding to your DataTable’s DefaultView, which is of type DataView. As a result, each row of your table will be bound to a DataRowView. If you look at the documentation for DataRowView you will find that it implements the IEditableObject interface which is the significant factor here. This interface allows you to perform trasnactional changes to your object, i.e. you can change the object’s properties within a ‘transaction’, then commit then all in a single atomic action. By default, when you bind to a DataGrid this occurs when the user finishes editing a row, either by moving focus or hitting Enter. In order to allow cell-by-cell changes, we need to commit each time the user moves from one cell to the next in the currently selected row.

The DataGrid exposes a CellEditEnding event which looks like a good candidate for this, from the event arguments we can locate the current EditingElement (i.e. the TextBox which now occupies or cell that is in edit mode), the cell’s Column and Row, and from here we can locate the Row.Item whcih is our bound DataRowView. You might think that we can just commit the change in this event handler, however, this is an ‘Ending’ event, not an ‘Ended’ event. In other words the value has not yet been written to the row. This catches me out far too often – as does its RowEditEnding counterpart!

So, if we cannot commit the edit here, how about the CurrentCellChanged event? however this event does not tell us which cell we just left. Although a simple combination of the two provides the effect we are after:

private DataRowView rowBeingEdited = null;
 
private void dataGrid_CellEditEnding(object sender,
                                  DataGridCellEditEndingEventArgs e)
{
    DataRowView rowView = e.Row.Item as DataRowView;
    rowBeingEdited = rowView;
}
 
private void dataGrid_CurrentCellChanged(object sender, EventArgs e)
{
    if (rowBeingEdited != null)
    {
        rowBeingEdited.EndEdit();
    }
}

With this change in place, changes are committed cell-by-cell and the two view remain synchronised:

cellsynchronized

You can download an example project, wpfdatagridcellbycellcommits, changing the file extension from .doc to .zip.

Regards, Colin E.