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!
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.
An instance of the above class is displayed in a simple form using the following XAML:
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:
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:
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.
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.