Colin Eberhardt's Technology Adventures

Using BindingGroups for greater control over input validation

November 28th, 2008

In a recent post on his blog Josh Smith described a technique for providing more meaningful error messages when the type conversion process fails within the binding framework. Consider the following problem; you bind an integer property of your object (Age for example) to a TextBox within your user interface. If the user enters a non-numeric value into the TextBox an exception is thrown within the binding framework when it attempts to parse this value. The framework provide s a way of catching validation exceptions, by setting ValidatesOnExceptions to true within a binding, however the error message provided is “Input string was not in a correct format.” – this is the sort of error message that a software engineer would understand, but not the majority of the population!

standardvalidation

Josh details a technique that can be used to provide more meaningful error messages. His technique uses a View-Model (the classes which massage your data into a form which is more amenable to your presentation technology), which binds a text ‘Age’ property to ensure that there are no type conversions issues in the binding, allowing the issue of parsing errors to be managed directly. This blog post illustrates an alternative technique to his approach, using the recently introduced feature of BindingGroups.

Take for example a very simple example, a Person class which has properties of Name and Age. This class implements IDataErrorInfo, allowing us to manage validation logic within the business objects themselves. This class has a pair of simple rules which are applied to the Age property.

public class Person : IDataErrorInfo, INotifyPropertyChanged
{
    private int age;
    public int Age
    {
        get { return age; }
        set {
            age = value;
            RaisePropertyChanged("Age");
        }
    }
 
    private string name;
    public string Name
    {
        get { return name; }
        set {
            name = value;
            RaisePropertyChanged("Name");
        }
    }
 
    #region IDataErrorInfo Members
    public string Error
    {
        get { return null; }
    }
 
    public string this[string columnName]
    {
        get {
            if (columnName == "Age")
            {
                if (Age < 0)
                    return "Age cannot be less than 0.";
                if (Age > 120)
                    return "Age cannot be greater than 120.";
            }
            return null;
        }
    }
    #endregion
 
    #region INotifyPropertyChanged Members
    ...
    #endregion
}

An instance of the above class is displayed in a simple form using the following XAML:

<Grid x:Name="RootElement">
  <Grid.BindingGroup>
    <BindingGroup>
      <BindingGroup.ValidationRules>
        <local:PersonValidationRule
          ValidationStep="ConvertedProposedValue"/>
      </BindingGroup.ValidationRules>
    </BindingGroup>
  </Grid.BindingGroup>
 
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="1.8*"/>
  </Grid.ColumnDefinitions>
 
  <Grid.RowDefinitions>
    <RowDefinition/>
    <RowDefinition/>
    <RowDefinition/>
  </Grid.RowDefinitions>
 
  <Label Content="Name:"/>
  <TextBox Grid.Column="1" LostFocus="TextBox_LostFocus"
       Text="{Binding Name, ValidatesOnDataErrors=true}"/>
 
  <Label Grid.Row="1" Content="Age:"/>
  <TextBox Grid.Row="1" Grid.Column="1" LostFocus="TextBox_LostFocus"
       Text="{Binding Age, ValidatesOnDataErrors=true}"/>
 
  <Label Grid.Row="2" Grid.ColumnSpan="2" Foreground="Red"
       Content="{Binding Path=(Validation.Errors)[0].ErrorContent,
               ElementName=RootElement}"/>
 
</Grid>

The TextBox bindings use ValidatesOnDataErrors, this ensures that the IDataErrorInfo interface methods on the Person class will be invoked, enforcing our Age rules. However, they do not handle exceptions thrown in the binding process, i.e. ValidatesOnExceptions is absent.

The interesting part of the above code is the BindingGroup which is present in the Grid element, i.e. at the ‘Form’ level. When you define a BindingGroup it is related to the DataContext of the element that it is defined against. The BindingGroup will then have access to all the other Bindings which relate to this DataContext. In the above example, the bindings inherit the Grid’s DataContext and are members of the same BindingGroup.

BindingGroups allow group level validation, this is useful for example if you have validation rules which relate to more than one property, for example “StartDate < EndDate". You can read all about BindingGroups on Vincent Sibal’s Blog.

In the above example, we do not have complex validation logic, so why use a BindingGroup?

When a ValidationRule is associated with a BindingGroup it has access to both the BindingExpressions, i.e. the “Name” and “Age” bindings in our example, and the BindingGroup instance itself. This class has some very useful methods like TryGetValue, which will attempt to get the bound value from the TextBox (or other bound UI control). However, the interesting part is that you can determine at what point in the binding pipeline your validation rule is applied, which will in turn determine whether you get back the raw value from the control, for example the string “34″, or the value after it has been parsed, i.e., an integer ’34′.

When BindingGroup was added to the API in .NET 3.5 SP1, the ValidationRule class was extended to add a ValidationStep property. This enumeration indicates at what stage within the binding pipeline a particular rule is invoked. The four possible enumeration values are detailed on MSDN. The one which we are interested in here is ConvertedProposedValue, which will mean that our rule is invoked after the binding framework has parsed the input string to an integer.

Here is our validation rule:

public class PersonValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value,
                                             CultureInfo cultureInfo)
    {
        BindingGroup bindingGroup = (BindingGroup)value;
        Person person = (Person)bindingGroup.Items[0];
 
        // validate the age
        object objValue = null;
        if (!bindingGroup.TryGetValue(person, "Age", out objValue))
        {
            return new ValidationResult(false, "Age is not a whole number");
        }
 
        // if we can retrieve the value - can we parse it to an int?
        int parseResult;
        if (!Int32.TryParse(objValue as string, out parseResult))
        {
            return new ValidationResult(false,
                            string.Format("Age is not a whole number"));
        }
 
        return ValidationResult.ValidResult;
    }
}

In the above code we ask the BindingGroup to provide its proposed value for the Age property. If the user has input a non-numeric value, TryParse will fail. We can then catch this failure and provide a suitable error message.

The final piece of the puzzle is dictating when this BindingGroup runs its associated rules. One of the primary purposes of the bindingGroup is to allow transactional editing of objects, for example within the WPF DataGrid it is used to commit a Row as a ‘atom’. We must manually commit this BindingGroup in order to run our rule, a ‘Submit’ button could be added to our form, but for simplicity in this example I simply commit as each TextBox loses focus:

private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    RootElement.BindingGroup.CommitEdit();
}

When using BindingGroups we can still of course validate each Binding independently, our ValidatesOnDataErrors still works.

The finished result is shown below, the screenshot on the right shows how our rule within the BindingGroup catches the case where the string cannot be parsed, and on the left where our Age rule enforced via IDataErrorInfo is violated.

bindinggroupvalidation

You can download a demo project with all of this code – bindinggroupvalidation, simple change the file extension from .doc to .zip.

*phew* – I thought I started writing a blog so that I could avoid writing lengthy articles!

Regards, Colin E.

Design time drag-and-drop binding is on its way

November 27th, 2008

In my opinion the lack of decent design-time tool support is currently hampering the adoption of WPF, that and the relatively small number of controls available to the developer out-of-the-box. The later is being addressed to a certain extent by the developer community, notably by Marlon Grech’s Avalon Controls Library and the WPF Toolkit. The former, design-time support, is something that is harder for the developer community to address, however Karl Shifflet’s XAML Power Toys, which add drag and drop form generation make a pretty good stab at it.

Despite this, people are adopting WPF even though it is not RAD yet. Paul Stovell provides a great demonstration of how productive WPF really is.

However; there are interesting developments at Microsoft, a video on Channel 9 reveals that Drag-Drop Data Binding will com to WPF in Visual Studio 2010. Exciting news indeed!

The screenshot below shows a Window which contains two ListViews in a master-detail configuration, which was entirely developed by drag and drop (minus a few code tweaks due to minor bugs in the VS 2010 CTP):

dragdropbinding

The demonstration details how DataSets, ADO.NET Entities, or Objects can be bound – with master-detail view achieved by ‘chaining’ CollectionViewSources, in the same way that you would a Windows Forms BindingSource. All this will sound familiar (and cosy) to a Windows Forms developer.

I am guessing that VS2010 will also provide the same drag and drop support for the WPF DataGrid.

While this looks like excellent news, drag and drop is not the be-all and end-all of RAD application development. Once you have dragged your UI elements onto the Window you would also want to be able to re-configure the source of the bindings, or the bound properties without having to touch the XAML. I do hope that VS 2010 brings this functionality also.

Either way, VS 2010 should open up WPF to a whole new audience.

Regards, Colin E.

Multiselect DataGrid with CheckBoxes

November 26th, 2008

I am currently very interested in the new WPF DataGrid which was released on codeplex recently. Someone posted an interesting question in the codeplex forums asking about whether it would be possible to configure the DataGrid so that a user can make multiple row selections via checkboxes which are associated with each row. I thought that this sounded like an excellent idea – afterall, the standard behaviour of ctrl-leftclick might be intuitive to the computer savvy, however you can bet the average user (which is certainly the majority) does not know this.

Fortunately the solution is quite simple to implement in WPF:

<dg:DataGrid ItemsSource="{Binding}">
  <dg:DataGrid.RowHeaderTemplate>
    <DataTemplate>
      <Grid>
        <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay,
                  RelativeSource={RelativeSource FindAncestor,
                  AncestorType={x:Type dg:DataGridRow}}}"/>
      </Grid>
    </DataTemplate>
  </dg:DataGrid.RowHeaderTemplate>
</dg:DataGrid>

The above code provides a DataTemplate for the RowHeader allowing us to render a CheckBox for each row. The IsChecked property uses a RelativeSource binding which navigates the Visual Tree to locate the first ancestor of type DataGridRow. From here the IsSelected property which dictates that the selected state of the row is available. The binding is TwoWay so that ctrl-leftclick behaviour is still visible.

The result is illustrated below:

multiselect

The above example is a concise illustration of the beauty of WPF. Performing the above customisation of the DataGridView in Windows Forms would be at least an afternoons work. However the solution is not without its problems, if you try the above you will find that the checkboxes are rather difficult to click on because the mouse cursor will be displaying the up-down arrow that indicates that it is currently over the gripper that allows you to specify the row height.

Finding the cause of this means delving deep into the DataGrid control templates …

The template for the DataGridRowHeader is given below (in edited form):

<Style x:Key="{x:Type dgp:DataGridRowHeader}"
       TargetType="{x:Type dgp:DataGridRowHeader}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type dgp:DataGridRowHeader}">
        <Grid>
          ... snipped header content + validation error indicator ...
          <Thumb x:Name="PART_TopHeaderGripper"
                 VerticalAlignment="Top"
                 Style="{StaticResource RowHeaderGripperStyle}"/>
          <Thumb x:Name="PART_BottomHeaderGripper"
                 VerticalAlignment="Bottom"
                 Style="{StaticResource RowHeaderGripperStyle}"/>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

The header template includes a pair of grippers. The visible state of these is toggled depending on the row’s location (i.e. there is no top gripper on the first row), and whether the DataGrid CanResizeRows is true.

The RowHeaderGripperStyle specifies a Transparent background for the grippers which renders them invisible. If we change this to Green we can see the culprits:

datagridselectproblem

In order to allow our Checkboxes to be clickable, we simply reduce the height of the grippers as follows:

<Style x:Key="RowHeaderGripperStyle" TargetType="{x:Type Thumb}">
  <Setter Property="Height" Value="2"/>
  <Setter Property="Background" Value="Green"/>
  <Setter Property="Cursor" Value="SizeNS"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Thumb}">
        <Border Padding="{TemplateBinding Padding}"
                Background="{TemplateBinding Background}"/>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Unfortunately this means that we have to duplicate the DataGrid parts; the DataGridRowHeader template and the above style, in order to perform this customisation. The Beauty of XAML and a Beast of a control template!

You can download the demo project, wpfdatagridmultiselect, changing the file extension from .doc to .zip.

Regards, Colin E.

P.S. You can achieve the same effect with a ListView as detailed in this blog post.