I am stuck in a seemingly common requirement. I have a WPF Prism (for MVVM) application. My model implements the IDataErrorInfo for validation. The IDataErrorInfo works great for non-numeric properties. However, for numeric properties, if the user enters invalid characters (which are not numeric), then the data doesn't even reach the model because wpf cannot convert it to numeric type.
So, I had to use WPF ValidationRule to provide user some meaningful message for invalid numeric entries. All the buttons in the view are bound to DelegateCommand of prism (in view model) and the enabling/disabling of buttons is done in View Model itself.
Now if a wpf ValidationRule fail for some TextBox, how do I pass this information to View Model so that it can appropriately disable buttons in the view ?
For MVVM I prefer to use Attached Properties for this type of thing because they are reusable and it keeps the view models clean.
In order to bind to the Validation.HasError property to your view model you have to create an attached property which has a CoerceValueCallback that synchronizes the value of your attached property with the Validation.HasError property on the control you are validating user input on.
This article explains how to use this technique to solve the problem of notifying the view model of WPF ValidationRule errors. The code was in VB so I ported it over to C# if you're not a VB person.
The Attached Property
Using The Attached Property in XAML
Now the property on your view model will be synchronized with Validation.HasError on your textbox.
Since .NET 4.5, ValidationRule has an overload of the Validate method:
You can override it and get the view model this way:
I encountered the same problem and solved it with a trick. See the converter below: