I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the ‘button’?
For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!
I can do this using my own ValidationEngine framework:
Customer customer = new Customer(); customer.FirstName = 'John'; customer.LastName = String.Empty; ValidationEngine.Validate(customer); if (customer.BrokenRules.Count > 0) { // do something display the broken rules! }
A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the IDataErrorInfo interface on your business object, using Bindings with
ValidatesOnDataErrors=true. For customizing the look of individual controls in the case of errors, set aValidation.ErrorTemplate.XAML:
This creates a
Windowwith twoTextBoxes where you can edit the first and last name of a customer. The ‘Save’ button is only enabled if no validation errors have occurred. TheTextBlockbeneath the button shows the current errors, so the user knows what’s up.The default
ErrorTemplateis a thin red border around the erroneous Control. If that doesn’t fit into you visual concept, look at Validation in Windows Presentation Foundation article on CodeProject for an in-depth look into what can be done about that.To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer.
Code Behind
An obvious improvement would be to move the
IDataErrorInfoimplementation up the class hierarchy, since it only depends on theValidationEngine, but not the business object.While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the ‘Save’ button as long as the user tries to enter invalid data.