Code should be transparent and intuitive for other developers to read. Therefore I searched for my current project – a Windows Phone 8 app to manage time sheets - a good solution to implement validation rules for my entities at a central point in my models. I found a nice implementation of a BindingModel from outcoldman at Codeproject. He looks at several validation technologies we have with Silverlight and describes them in the mentioned article in detail. Most of my classes based on this article which I have expanded by some new behaviors and properties.
My resulting validation code in the constructor of my models looks like this:
INotifyDataErrorInfo interface came with Silverlight 4 which can be used for synchronous and asynchronous validation. Microsoft suggestion is, that new entity classes should implement INotifyDataErrorInfo for the added flexibility instead of implementing IDataErrorInfo. The IDataErrorInfo support enables you to use many existing entity classes that are written for the full .NET Framework.
The first step of the validation rule implementation is to expand our properties for storing validation rules and manage error messages.This is done by the PropertyValidation class:
The next step is to implement a generic
BindingModelBase class which will implement the
INotifyDataErrorInfo interfaces. This class contains also two fields for storing the added validation rules and validation errors:
Show the errors
To show the errors at the user interface I used the ErrorMessages and HasError property. At my View I only have to attach a BindingValidationError event handler which calls an extension method to mark the properties which raises an error.
But how to show a list of the error messages for the corresponding fields?
To achieve this, I made a converter (our swiss knife :-) which extracts the error messages from the ErrorMessages property and populate that to a user control which shows the error list for one property (the parameter of the converter contains the bounded property name for which I want to display the error messages).
The converter code: