Today I've looked into the MSDN example for validation on WPF TextBox inputs (see also: http://msdn.microsoft.com/en-us/library/ms753962.aspx).
In my own application I bind the DataContext of the view to a ViewModel, using the MVVM pattern. Certain TextBoxes are databind to properties on the ViewModel and have specific ValidationRules on them.
What I've discovered is when a value gets invalidated, after it's succesfully validated before, the old value will remain in the ViewModel. Very unusefull in my opinion, because values are used for command execution for example.
This exact problem of mine also applies on the given MSDN example. The value of a TextBox is only send back to it's source after it's succesfully validated. I'd like to keep the validation logic, but it should always update the source. Is this possible?
Thanks in advance.
As Rachel and Henk pointed out, that is how WPF Validation Rules are built. If validation fails, it won't write the value to the property.
As for why they decided to build it that way, it's probably because they want consistent behavior for when validation fails. Sometimes the value on the view is invalid (e.g. a negative Age) but it could be written into the property. Other times it is invalid in a way that could not possibly be written into the property (e.g. an Age of "foo" cannot be converted to an int). It might be confusing if the behavior was "write the value to the property if possible".
Like you, I would prefer it if my ViewModel got updated whenever possible, regardless of validation errors. Business objects are a different matter, but "Fort Knox ViewModels" seem strange to me because invalid input is not just OK, it is expected. Usually in my ViewModel I want to know the "current value", not the "last valid value". This is one of the reasons I don't like ValidationRules.
Validation is there to ensure that data entered is valid for the property specified. If data is invalid, it should not be stored in the property.
For example, if someone types a letter into a TextBox bound to an Integer field, the application should not try and put the character into an int because an exception would be thrown.
An alternative is to have a separate IsValid()
method that does some manual validation checks on your data and returns a true/false if the data is valid or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With