Before 3.5 SP1, the binding validation system worked with only one binding at a time. What made this difficult in some scenarios was when validation was required on a set of bound objects. Some typical examples that come to mind are a form of data items that are submitted all at once or a ListView or DataGrid row that is committed all at once. You can put a validation rule on each bound object and validate their values individually but there was no readily available way in the binding validation system to validate multiple objects together. Now in 3.5 SP1 a solution has been created for this, Binding Groups.
What is it?
A BindingGroup encapsulates and has access to a set of related bindings. These related bindings are bindings that share the same data context as the BindingGroup and/or bindings that have explicitly declared membership to the BindingGroup. With this set of bindings, the BindingGroup can now provide services such as validation of all the encapsulated bindings together and transactional editing.
How do I define a BindingGroup?
We will use an example to illustrate how to define a BindingGroup. Let’s say this is the data context that I will use (I just went canoeing recently which influence my choice of data):
With this data I want to use it in a form to be filled in by the customer. Here is the xaml (I only put the relevant information for this example):
As I said in the Motivation section, we can add validation to each binding and validate them individually, but there wasn’t a built in mechanism to validate them as a group. To do that, we can add a BindingGroup to the Grid:
Assuming that I’ve set the Grid.DataContext to be an instance of BoatRentalCustomer, the BindingGroup I set on the Grid will have access to all the bindings I set within the Grid. This example shows how the BindingGroup gets bindings from the same DataContext but it is also possible to get bindings through explicit membership declaration like this slightly modified example below:
I named the BindingGroup, “FormBindingGroup”, and added a binding to the FontSize property on one of the TextBox elements. Notice that in the binding I explicitly declare BindingGroupName to be set to “FormBindingGroup”. By doing this, the BindingGroup will have access to the bindings under the same DataContext as well as the bindings associated with it by the same BindingGroupName. The ability to declare explicit membership to a BindingGroup are for scenarios where bindings don’t use DataContext (explicit Source or ElementName like in the example above) and/or bindings that use a different DataContext that want to participate in the same group validation.
From the previous example you saw that Grid had a property named BindingGroup. You may be wondering where BindingGroup is actually defined. BindingGroup has been added to FrameworkElement and FrameworkContentElement so it can be associated with a set of bindings on a per element basis.
It has also been added to ItemsControl so it can be associated with a set of bindings per each generated container. The pattern is similar to ItemTemplate.
And as you saw the use of BindingGroupName, that property has been defined in BindingBase.
How do I use it? (Part 1)
So now I know where to define a BindingGroup and how bindings get associated with it, but how do I use it? Let’s first look at the BindingGroup class and then dig into the common APIs and common scenarios. Here is the BindingGroup class:
You have access to the associated bindings through the BindingExpressions property and can set group validation rules through the ValidationRules property. You may have notice all these transactional methods in this class such as BeginEdit, CancelEdit, etc. Well, as part of group validation you have the ability to control whether the new data to that item is committed as a whole and/or reverted back to its previous state. The two major areas of BindingGroup that I want to get into are its validation rules and how its methods are used to update the binding sources. First, let’s discuss validation.
The ValidationRule class has been updated with a couple APIs to work with BindingGroup. Here are the new APIs:
The ValidationStep property is used to let ValidationRule know when to apply the validation. RawProposedValue means the rule is applied to the unconverted value. This is the default step which also was the current behavior for ValidationRule prior to this feature. ConvertedProposedValue means the rule is applied to the converted value, UpdatedValue means the rule is applied after writing to the source, and CommittedValue means the rule is applied after committing changes. ValidatesOnTargetUpdated is used to trigger validation when the source is updating the target.
So now we have an idea of how validation rule may be used but how does this relate to the transactional methods of BindingGroup? Note that to use a BindingGroup for transactional editing, you should define IEditableObject on your data item.
BeginEdit, CancelEdit, and CommitEdit work similar to IEditableCollectionView’s versions where they will call IEditableObject.BeginEdit, IEditableObject.CancelEdit, and IEditableObject.EndEdit respectively on the data item. In addition to CommitEdit, you also have UpdateSources and ValidateWithoutUpdate. These three methods (CommitEdit, UpdateSources, and ValidateWithoutUpdate) are the main methods that you will call to validate and update your source. That brings up a point on how bindings update in a BindingGroup. UpdateSourceTrigger for bindings that belong to the BindingGroup are set to Explicit by default. That means you will need to use the BindingGroup APIs to update the bindings (CommitEdit or UpdateSources). Validation and updating methods work like this:
· ValidateWithoutUpdate: runs all validation rules marked as RawProposedValue or ConvertedProposedValue.
· UpdateSources: does the same as ValidateWithoutUpdate, and then if no errors were found, it writes all the values to the data item and runs the validation rules marked as UpdateValue.
· CommitEdit: does the same as UpdateSources, and then runs the rules marked as CommittedValue.
How do I use it? (Part 2)
Ok, we made it this far. So I know where to define my BindingGroup, how to setup when I want my validation rules ran and how to update my bindings. Let’s look at what kinds of things I can do to actually validate the item inside the ValidationRule.Validate method.
The value input parameter to Validate is the actual BindingGroup. With the BindingGroup you can query for the data on the item. The important BindingGroup APIs for the actual validation include Items, GetValue, and TryGetValue. The Items collection contains the unique data items used by the bindings in the group. GetValue looks for the binding that uses the given item and propertyName parameter values and returns the value appropriate to the current validation step. So for example, if the validation step is RawProposedValue or ConvertedProposedValue, the data source has not been updated yet when the Validate method is called, but by querying for the value using GetValue you can get what the value will be (as long as it passes validation). Here is an example Validate method:
You’ll notice that I am assuming the data item is Items. If the BindingGroup has bindings from more than one data source then you will have to handle that as the Items collection will be greater than one. I’ve also been pretty optimistic about getting the proposed values as well as parsing the DateTime. This example is for demonstration purposes only but in a production level application you will probably want to use TryGetValue and TryParse. So inside the Validate method I have access to the entire item and in the example I validate the start and end date together.
Where we are…
Hopefully I still have your attention after all that. I know it’s a lot to go through. Just to summarize a bit, a BindingGroup enabled you to validate data at the item-level as opposed to the property-level. This is possible because the BindingGroup has access to all the bindings associated with the data item (assuming you set the BindingGroup that way). BindingGroup is available on all FrameworkElements, FrameworkContentElements, and ItemsControls. You set the validation rules on the actual BindingGroup and in the ValidationRule.Validate method you are given the BindingGroup where you can query for all the properties on the item being validated. I’ve attached a small sample to demonstrate some of the concepts discussed here.
So what’s left? Well, there are two more important topics that should be discussed. One is the new additions to validation feedback and the other is how BindingGroup works in conjunction with IEditableCollectionView. I will save both these topics for another post as there is enough here to digest. This does cover about 95% of the new APIs relating to BindingGroup so there isn’t too much more to cover. = )
However, BindingGroup and IEditableCollectionView can be a bit confusing on when and how to use them so I do want to talk more on that. Read more on BindingGroup and IEditableCollectionView here. And you can read on BindingGroup and ValidationFeedback here.