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 ?
You must specify custome user control depending bind type property. For example if your property is int type you must place control that not allow diferent value except intenger type.
The logic you may put in PreviewTextInput="NumberValidationTextBox".
just insert your logic or place custome control and you are done.
Defently must implement mvvm validation too.
I have the same problem with you, but I solve in another way, I use the Triggers to disable the button when the input is invalid. Meanwhile, the textbox binding should use
ValidatesOnExceptions=true
Implement
IDataErrorInfo
in your model or Viewmodel depending logic of binding property. You may implement in both classes.Implement this too in your base validation class. Here validation will trigger when binding
IDataErrorInfo
does not work.Next, add global class
xaml
If you provide a custom
ValidationRule
implementation you can store the value it received, as well as storing the last result. PseudoCode:Nirvan
The simplest way to solve this particular issue is to use a numeric textbox, which prevents the user from entering an invalid value (you can either do this via a Third Party Vendor, or find an open source solution, such as a class derived from Textbox that suppresses non numeric input).
The second way to handle this in MVVM without doing the above, is to define another field in you ViewModel which is a string, and bind that field to your textbox. Then, in the setter of your string field you can set the Integer, and assign a value to your numeric field:
Here is a rough example: (NOTE I did not test it, but it should give you the idea)
Someone's solved it here (unfortunately its in VB) by creating a dependency property HasError in the VM which seems to be bound to the Validation.HasError. I don't completely understand it yet but it may help you:
http://wpfglue.wordpress.com/2009/12/03/forwarding-the-result-of-wpf-validation-in-mvvm/