【问题标题】:WPF get HasError of a binding from source propertyWPF 从源属性获取绑定的 HasError
【发布时间】:2018-09-04 12:27:00
【问题描述】:

给定一个具有直接绑定和验证的文本框:

<TextBox Content="{Binding ProblematicText}" ValidationRule="...">

以及我的 DataContext 中的源属性:

public string ProblematicText
{
    // ...
}

在代码中我必须使用属性“ProblematicText”的值,除非 TextBox 在其 ValidationRule 中有错误。

如何从代码中访问BindingExpression.HasError 或简单地实现这一点?

【问题讨论】:

  • ps:我显然没有办法使用BindingOperations.GetBindingExpression(dependencyObject, dependencyProperty);,因为它们是“未知的”。
  • 我以这种方式访问​​各种属性。我在 XAML(视图)中绑定属性,但在 C#(视图模型)中,我不知道哪个 gui 元素位于哪个属性后面。
  • 您应该在视图模型中处理验证逻辑。看我的回答。

标签: c# wpf validation binding


【解决方案1】:

视图模型不知道(当然也不应该知道)任何可能在视图中定义的验证规则。因此,如果 ProblematicText 在视图模型中定义,您应该在此类中执行验证。

摆脱验证规则并在您的视图模型中实现INotifyDataErrorInfo 接口。下面是一些应该给出想法的链接。

WPF 4.5:使用 INotifyDataErrorInfo 接口验证数据: https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx

How to use a validation between two datepicker?

【讨论】:

    猜你喜欢
    • 2011-04-04
    • 2015-01-22
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多