I’m working on the validation rules for some data input forms in WPF/XAML. I’ve been able to get the user experience I would like, by explicitly applying validation rules to the field bindings:
<Binding
Path="qtyoffset"
NotifyOnValidationError="True"
ValidatesOnDataErrors="True"
UpdateSourceTrigger="PropertyChanged"
>
<Binding.ValidationRules>
<utility:DecimalValidationRule precision="1" />
</Binding.ValidationRules>
</Binding>
With the above, the field is validated on every key press. If the user enters a ‘X’, the field is immediately flagged as invalid, the error message shows up in the appropriate place, the “commit” button is immediately disabled, etc. All nice and slick. Same thing happens if the user enters two digits after the decimal point, enters two decimal points, etc.
My only problem is the verbosity. The above binding code needs to be provided for every field, and if it’s not quite right on one field, that one field will work not quite right. I’d much rather specify only the binding path, and have the rest of it added automatically. Set NotifyOnValidationError, ValidatesOnDataErrors, and UpdateSourceTrigger on every binding, set whichever validation rules are appropriate for the specific data type, depending on the type it is bound to. Or, at least, according to the type I specify in XAML.
I’m thinking about the way I would do validation in JQuery. Rather than statically listing all the validation rules on each input element, I’d set a number of classes. And then, on load, I’d use JQuery’s DOM search capabilities to find every input element with a specific class set, and dynamically add the appropriate validation functionality.
XAML provides a very nice way of providing this sort of concise configuration for display elements, using Styles and Setters. But that doesn’t work for Bindings.
Is there a reasonable alternative?
Short answer: No, not really.
However you can do 2 things:
You can put
in resources and access them as
StaticResource, to factor out redundant information, and then you could change all of those properties in one place.<TextBox Text={local:DecimalBinding Path=qtyoffset} />HTH,
Bab.