Tuesday, November 2, 2010

WPF ValidationTemplate

I've read a lot of different WPF validation articles, and I've come to my own conclusion that the most simple, but also flexible solution is to use the combination of the IDataErrorInfo interface on my business objects, and use converters and simple data type validators for data type conversions.


That being said, I've notice a significant number of example  classes have not implemented a very good ValidationTemplate! I've seen the following Binding statement in the majority of the binding template examples I've seen:



Path=(Validation.Errors)[0].ErrorContent


Can you see what is wrong with this statement? Its the index based access o the Errors collection! This type of binding won't effect the functionality. It will actually work fine, but if you watch the output window with the index accessing solution, you'll notice as soon as you enter a valid value (which should be most of the time!) an exception is getting swallowed by the WPF framework! (as shown below)

System.Windows.Data Error: 16 : Cannot get ‘Item[]‘ value (type ‘ValidationError’) from ‘(Validation.Errors)’ (type ‘ReadOnlyObservableCollection`1′). BindingExpression:Path=(0).[0].ErrorContent; DataItem=’TextBox’...

We can correct this simple flaw with the following correction:


Path=(Validation.Errors).CurrentItem.ErrorContent


This accesses the ObservableCollection of errors, and the CurrentItem property correctly passes a null, instead of throwing an index out of range exception.

Always keep in mind that WPF will swallow exceptions that are thrown while binding, but you can still see them within the output window while debugging!

No comments:

Post a Comment