The third and final Data Binding topic I’d like to cover for now is Data Validation. I’ll modify the code discussed yesterday we’re going to validate the Quantity on Hand field, already marked as two-way (that is, the user can enter a new value and it is stored in the underlying business object – the current book).
Our goal is to capture and handle two types of errors
- Exceptions thrown from the Binding Engine
- Exceptions thrown from the Binding Source
An example of an exception the Binding Engine would throw would be were the user to enter letters where an integer value is expected
Binding Source exceptions would be created by the author of the Binding Source class (the Book Class) to ensure data integrity. In our case, we might throw an exception if we are handed a negative value for Quantity on hand. Thus, we might modify the set accessor for Quantity on hand as follows,
To manage both of these types of errors need to take 3 steps
- Identify the error handler either in the control or higher in the visiblity hierarchy (e.g., a container; in this case the grid that contains the text box)
- Set NotifyOnValidationError and ValidateOnException to true. The latter tells teh Binding Engine to create a validation error event when an exception occurs. The former tells the Binding Engine to raise teh BindingValidationError event when a validation error occurs.
- Create the event handler named in step 1
Identify the Handler
We’ll put the identifier of the handler in the grid so that it may be shared by all the controls within the grid.
<Grid x:Name="LayoutRoot" Background="White" BindingValidationError="LayoutRoot_BindingValidationError" >
Set NotifyOnValidationError and ValidateOnException
These are set as part of the binding syntax in the control itself,
Create the Event Handler
The event handler named in the grid is implemented in the associated code-behind file,
Delegation of Responsibility
Notice the careful delegation of responsibility.
The Binding class knows that it is handling validation and some first approximation of validity (integers aren’t text) but it turns to the Book class for further validation (e.g, Quantity on Hand can’t be negative). If it finds that the value is invalid it raises an event, but it is up to the UI to handle that event and decide how to display that there is invalid data to the user.
Page.xaml in this case manages that by refusing to move to the next book and turning the input box red. There are a thousand other things it could do, but the key here is separation of responsibility. The UI doesn’t know why the data is invalid, only that it is.
Here is what it looks like when you enter invalid data and hit the Change Book button
As you can see, the entry box turns red, and the book does not change until the user fixes the data entered.
For those of you who want to copy and paste, here are all the changes