Microsoft WPF includes a data binding framework that provides a simple declarative mechanism to associate and validate data with UI components – read some good tips and tricks here.
This works well very well for simple form validation but sometimes you may want to perform a more complex series of validations and reflect the failures back to the user in a similar manner to the field level validation. For example, a particular combination of fields may result in breaking a business rule for that particular user and the client has asked you to highlight all of these fields with a similar message. In this situation additional validation when the form is submitted may be the simplest solution, so we need to carry out some process like this:
- Perform validation of business object obtained from data binding.
- Interpret validation results.
- Flag multiple fields as being incorrect.
To perform the last step you need to know how to programmatically force binding errors. I googled and binged for ages trying to find this information so here is the simple recipe.
- Make sure the fields that the fields that need to show binding errors have a mode of TwoWay or OneWayToSource in their binding expression.
- Make sure the fields that need to show binding errors have the ValidatesOnDataErrors set to true in their binding expressions.
- Force the validation errors when the form is submitted like this
ValidationError validationError = new ValidationError(emptyValidationRule, textBox.GetBindingExpression(TextBox.TextProperty), "Error message", null); Validation.MarkInvalid(textBox.GetBindingExpression(TextBox.TextProperty),Â validationError);
I am using an emptyValidationRule just to satisfy the type signature here. It is never actually used because my business validation is carried out elsewhere. The emptyValidationRule is a simple implementation of a ValidationRule that always fails.
To remove a validation error from a field
This approach can also help if you need to validate that a ComboBox value is actually selected when no default value has been provided. Validation rules only fire automatically if data binding actually occurs, that means the ComboBox must actually be used. You could force databinding to occur like this:
when the ComboBox loses focus. However, if the user just uses the mouse to press the form submit button, the combobox will never gain or lose focus so no validation will take place. To work around this you can validate in the way I have shown above or perform UpdateTarget operations on all of the ComboBox controls in the form when submit is pressed.