简体   繁体   English

什么是IDataErrorInfo以及它如何与WPF一起使用?

[英]What is IDataErrorInfo and how does it work with WPF?

While working on some custom validators in WPF, one of my co-workers pointed me out the IDataErrorInfo. 在WPF中处理一些自定义验证器时,我的一位同事向我指出了IDataErrorInfo。 I have a sample view in XAML that has a textbox and a button. 我在XAML中有一个示例视图,它有一个文本框和一个按钮。 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. 我的同事建议在我的视图的presentor中扩展IDataErrorInfo并为'Item'和'Error'属性编写自定义逻辑将解决我的问题。 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? 在我将这个结合到我的代码中之前,我想我应该理解IDataError信息是如何工作的以及实现这个接口提供必要的钩子以触发自定义验证逻辑的原因是什么? Some help with this concept would be extremely helpful! 对这个概念的一些帮助将非常有帮助!

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. IDataErrorInfo是一个类可以实现的接口,以便通知订阅者特定属性的错误信息,以及类级别的错误。

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. 如果为用作DataContext的类(即:MVVM中的ViewModel)实现此操作,则可以将控件的UpdatesOnValidationError设置为true,并设置自定义模板以在出现错误时以不同方式显示该项。 WPF handles the plumbing for you. WPF为您处理管道。

Here is a short tutorial showing the entire process . 这是一个简短的教程,展示了整个过程

As stated before the IDataErrorInfo interfaces provides validation for data-bound ViewModel properties. 如前所述,IDataErrorInfo接口为数据绑定的ViewModel属性提供验证。 You can implement custom validation rules or utilize the validation attributes available in System.ComponentModel.DataAnnotations. 您可以实现自定义验证规则或利用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. 我发现很多关于这个主题的教程都有额外的“绒毛”,并且他们可能会让那些从WPF开始的人很难掌握这个概念。 I wrote a straight to the point tutorial at refactorthis.net called WPF Validation tutorial for the rest of us. 我在refactorthis.net上直接写了一篇关于我们其他人的WPF验证教程的教程。 Learn to use IDataErrorInfo to automatically validate your views. 学习使用IDataErrorInfo自动验证您的视图。

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF) . 您可能对WPF应用程序框架(WAF)BookLibrary示例应用程序感兴趣。 It shows how to use validation in WPF and how to control the Save button when validation errors exists. 它显示了如何在WPF中使用验证以及如何在存在验证错误时控制“保存”按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM