So you’ve built up your nice new fancy custom control, and some Dependency Properties for your users to bind there data to, what else could you want? How about validation? Turns out that the control base class is all ready set up for this exact scenario. There is only one step required: Create the Visual states. Just add a visualstategroup called ValidationStates
and a state for each of Valid
, InvalidUnfocused
and InvalidFocused
corresponding to how you want your control to behave when in each of those states. You can even add these attributes into your class cs file to aid in blending your control:
[TemplateVisualState(GroupName = "ValidationStates", Name = "Valid")]`
[TemplateVisualState(GroupName = "ValidationStates", Name = "InvalidUnfocused")]
[TemplateVisualState(GroupName = "ValidationStates", Name = "InvalidFocused")]
I suggest checking out how some of your favourite controls are templated for validation, such as CheckBox and TextBox, to build a default template that would fit in with the existing control validation states. This supports Exception Validation, IDataErrorInfo
, INotifyDataErrorInfo
including using INotifyDataErrorInfo
asynchronously. Of course you need to set up your bindings correctly using the ValidatesOnExceptions=true
, NotifyOnValidationError=true
binding properties.
One quick Gotcha, that I found when testing this: make sure that you are binding on the property that reports the errors, especially when using the INotifydataErrorInfo
. You need to explicitly bind the datacontext to your validation object to get class level validation to trigger the control’s validation. This may be true for textboxes and other built-in controls as well, but I haven’t verified this theory yet.
There is an excellent Whitepaper on validation using INotifyDataErrorInfo
at silverlight.net/learn/whitepapers as well as lots of posts around the web, if you take the time to look (or search). Jesse Liberty also has a validation blog as part of a templates and visual states series on his blog, which i referred to when building up my own validation controls and viewmodels using INotifyDataErrorInfo
.