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

时间:2020-03-05 18:53:38  来源:igfitidea点击:

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

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

解决方案

回答

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

在这里阅读更多

回答

还要检查这篇文章。据说微软从他们的模式和实践中发布了他们的企业库(v4.0),其中涵盖了验证主题,但是上帝知道为什么他们不包括对WPF的验证,因此我将指导博客文章解释了作者的内容。做了适应。希望这可以帮助!

回答

个人而言,我正在使用异常处理验证。它需要执行以下步骤:

  • 在数据绑定表达式中,我们需要添加" ValidatesOnException = True"
  • 在要绑定到的数据对象中,需要添加DependencyPropertyChanged处理程序,在其中检查新值是否满足条件-如果不满足,则恢复到对象的旧值(如果需要)并引发异常。
  • 在用于在控件中显示无效值的控件模板中,可以访问"错误收集"并显示异常消息。

这里的技巧是仅绑定到从DependencyObject派生的对象。 INotifyPropertyChanged的简单实现无法正常工作,因为框架中存在一个错误,该错误会阻止我们访问错误集合。

回答

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

回答

从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.

该文档继续说明了如何实现IDataErrorInfo和INotifyDataErrorInfo。