views:

12095

answers:

5

I have a very simple WPF application in which I am using data binding to allow editing of some custom CLR objects. I am now wanting to put some input validation in when the user clicks save. However, all the WPF books I have read don't really devote any space to this issue. I see that you can create custom ValidationRules, but I am wondering if this would be overkill for my needs.

So my question is this: is there a good sample application or article somewhere that demonstrates best practice for validating user input in WPF?

+12  A: 

I think the new preferred way might be to use IDataErrorInfo

Read more here

rudigrobler
thanks, looks like a good article
Mark Heath
I've also found the Cinch framework (http://cinch.codeplex.com/), which includes a demo of best practices validation in WPF+MVVM, and uses IDataErrorInfo
Mark Heath
+2  A: 

Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!

murki
+3  A: 

personaly, i'm using exceptions to handle validation. it requires following steps: 1. in your data binding expression, you need to add "ValidatesOnException=True" 2. in you data object you are binding to, you need to add DependencyPropertyChanged handler where you check if new value fulfills your conditions - if not - you restore to the object old value (if you need to) and you throw exception. 3. in your control template you use for displaying invalid value in the control, you can access Error collection and display exception message.

the trick here, is to bind only to objects which derive from DependencyObject. simple implementation of INotifyPropertyChanged wouldn't work - there is a bug in the framework, which prevents you from accessing error collection.

Greg
+1  A: 

Also, Karl Shifflet has written a very good article on Input Validation for M-V-VM, you may want to check it out as well.

murki
A: 

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use validation in WPF and how to control the Save button when validation errors exists.

jbe