What is IDataErrorInfo and how does it work with W

2019-05-01 04:25发布

问题:

While working on some custom validators in WPF, one of my co-workers pointed me out the IDataErrorInfo. I have a sample view in XAML that has a textbox and a button. Based on the value in the textbox I would like the button to be either enabled or disabled. My co-worker suggested that extending the IDataErrorInfo in the presentor of my view and writing custom logic for the 'Item' and 'Error' properties would solve my problem. Before I could incorporate this in my code, I thought I should understand how IDataError info works and what is it about implementing this interface that provides the necessary hooks to trigger the custom validation logic? Some help with this concept would be extremely helpful!

回答1:

IDataErrorInfo is an interface that a class can implement in order to notify subscribers of error information for a specific property, as well as errors at the class level.

If you implement this for the class that's used as your DataContext (ie: the ViewModel in MVVM), you can set UpdatesOnValidationError to true for controls, and set a custom template to display the item differently if there are errors. WPF handles the plumbing for you.

Here is a short tutorial showing the entire process.



回答2:

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.



回答3:

As stated before the IDataErrorInfo interfaces provides validation for data-bound ViewModel properties. You can implement custom validation rules or utilize the validation attributes available in System.ComponentModel.DataAnnotations.

I've found that many of the tutorials on the subject are convoluted with extra "fluff" and they can make it hard for someone starting out with WPF to grasp the concept. I wrote a straight to the point tutorial at refactorthis.net called WPF Validation tutorial for the rest of us. Learn to use IDataErrorInfo to automatically validate your views.