WPF Data Binding and Validation Rules Best Practices
I have a very simple WPF application in which I am using data binding to allow editing of some custom CLR objects. I am now wanting to put some input validation in when the user clicks save. However, all the WPF books I have read don't really devote any space to this issue. I see that you can create custom ValidationRules, but I am wondering if this would be overkill for my needs.
So my question is this: is there a good sample application or article somewhere that demonstrates best practice for validating user input in WPF?
I think the new preferred way might be to use IDataErrorInfo
Read more here
From MS's Patterns & Practices documentation:
Data Validation and Error Reporting
Your view model or model will often be required to perform data validation and to signal any data validation errors to the view so that the user can act to correct them.
Silverlight and WPF provide support for managing data validation errors that occur when changing individual properties that are bound to controls in the view. For single properties that are data-bound to a control, the view model or model can signal a data validation error within the property setter by rejecting an incoming bad value and throwing an exception. If the ValidatesOnExceptions property on the data binding is true, the data binding engine in WPF and Silverlight will handle the exception and display a visual cue to the user that there is a data validation error.
However, throwing exceptions with properties in this way should be avoided where possible. An alternative approach is to implement the IDataErrorInfo or INotifyDataErrorInfo interfaces on your view model or model classes. These interfaces allow your view model or model to perform data validation for one or more property values and to return an error message to the view so that the user can be notified of the error.
The documentation goes on to explain how to implement IDataErrorInfo and INotifyDataErrorInfo.
personaly, i'm using exceptions to handle validation. it requires following steps:
- in your data binding expression, you need to add "ValidatesOnException=True"
- in you data object you are binding to, you need to add DependencyPropertyChanged handler where you check if new value fulfills your conditions - if not - you restore to the object old value (if you need to) and you throw exception.
- in your control template you use for displaying invalid value in the control, you can access Error collection and display exception message.
the trick here, is to bind only to objects which derive from DependencyObject. simple implementation of INotifyPropertyChanged wouldn't work - there is a bug in the framework, which prevents you from accessing error collection.