.net WPF 数据绑定和验证规则最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/63646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:51:15  来源:igfitidea点击:

WPF Data Binding and Validation Rules Best Practices

.netwpfdata-bindingvalidation

提问by Mark Heath

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.

我有一个非常简单的 WPF 应用程序,我在其中使用数据绑定来允许编辑一些自定义 CLR 对象。我现在想在用户单击保存时进行一些输入验证。然而,我读过的所有 WPF 书籍都没有真正为这个问题留出任何篇幅。我看到您可以创建自定义 ValidationRules,但我想知道这对我的需求来说是否太过分了。

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

所以我的问题是:是否有一个很好的示例应用程序或文章展示了在 WPF 中验证用户输入的最佳实践?

采纳答案by rudigrobler

I think the new preferred way might be to use IDataErrorInfo

我认为新的首选方式可能是使用 IDataErrorInfo

Read more here

在这里阅读更多

回答by Pat

From MS's Patterns & Practices documentation:

来自 MS 的模式与实践文档

Data Validation and Error Reporting

Your view model or model will often be required to perform data validation and to signal any data validation errors to the view so that the user can act to correct them.

Silverlight and WPF provide support for managing data validation errors that occur when changing individual properties that are bound to controls in the view. For single properties that are data-bound to a control, the view model or model can signal a data validation error within the property setter by rejecting an incoming bad value and throwing an exception. If the ValidatesOnExceptions property on the data binding is true, the data binding engine in WPF and Silverlight will handle the exception and display a visual cue to the user that there is a data validation error.

However, throwing exceptions with properties in this way should be avoided where possible. An alternative approach is to implement the IDataErrorInfo or INotifyDataErrorInfo interfaces on your view model or model classes. These interfaces allow your view model or model to perform data validation for one or more property values and to return an error message to the view so that the user can be notified of the error.

数据验证和错误报告

您的视图模型或模型通常需要执行数据验证并向视图发出任何数据验证错误的信号,以便用户可以采取行动纠正它们。

Silverlight 和 WPF 支持管理在更改绑定到视图中的控件的单个属性时发生的数据验证错误。对于数据绑定到控件的单个属性,视图模型或模型可以通过拒绝传入的错误值并抛出异常来在属性设置器中发出数据验证错误的信号。如果数据绑定的 ValidatesOnExceptions 属性为 true,WPF 和 Silverlight 中的数据绑定引擎将处理异常并向用户显示存在数据验证错误的视觉提示。

但是,应尽可能避免以这种方式抛出具有属性的异常。另一种方法是在您的视图模型或模型类上实现 IDataErrorInfo 或 INotifyDataErrorInfo 接口。这些接口允许您的视图模型或模型对一个或多个属性值执行数据验证并向视图返回错误消息,以便用户可以收到错误通知。

The documentation goes on to explain how to implement IDataErrorInfo and INotifyDataErrorInfo.

该文档继续解释如何实现 IDataErrorInfo 和 INotifyDataErrorInfo。

回答by Greg

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.
  1. 在您的数据绑定表达式中,您需要添加“ValidatesOnException=True”
  2. 在您绑定到的数据对象中,您需要添加 DependencyPropertyChanged 处理程序,您可以在其中检查新值是否满足您的条件 - 如果没有 - 您恢复到对象旧值(如果需要)并抛出异常。
  3. 在用于在控件中显示无效值的控件模板中,您可以访问错误集合并显示异常消息。

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.

这里的技巧是只绑定到从 DependencyObject 派生的对象。INotifyPropertyChanged 的​​简单实现不起作用 - 框架中有一个错误,它阻止您访问错误集合。

回答by murki

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!

另请查看这篇文章。据说微软从他们的模式和实践中发布了他们的企业库 (v4.0),其中涵盖了验证主题,但天知道为什么他们没有包含对 WPF 的验证,所以我指导您阅读的博客文章解释了作者的内容确实适应了它。希望这可以帮助!

回答by jbe

You might be interested in the BookLibrarysample 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.

您可能对WPF 应用程序框架 (WAF)BookLibrary示例应用程序感兴趣。它展示了如何在 WPF 中使用验证以及如何在存在验证错误时控制“保存”按钮。

回答by Alex Pollan

If your business class is directly used by your UI is preferrable to use IDataErrorInfo because it put logic closer to their owner.

如果您的 UI 直接使用您的业务类,则最好使用 IDataErrorInfo,因为它使逻辑更接近于它们的所有者。

If your business class is a stub class created by a reference to an WCF/XmlWeb service then you can not/must not use IDataErrorInfo nor throw Exception for use with ExceptionValidationRule. Instead you can:

如果您的业务类是通过对 WCF/XmlWeb 服务的引用创建的存根类,那么您不能/不得使用 IDataErrorInfo 或抛出异常以与 ExceptionValidationRule 一起使用。相反,您可以:

  • Use custom ValidationRule.
  • Define a partial class in your WPF UI project and implements IDataErrorInfo.
  • 使用自定义验证规则。
  • 在 WPF UI 项目中定义分部类并实现 IDataErrorInfo。