【问题标题】:How do I detect ViewModel binding errors in code?如何检测代码中的 ViewModel 绑定错误?
【发布时间】:2015-09-09 04:00:16
【问题描述】:

假设我有一个 ViewModel

class MyViewModel { public DateTime? InvoiceDate { get; set; } }

并且这个 ViewModel 被绑定到一个文本框:

<TextBox Text="{Binding InvoiceDate}" />

现在当用户输入2015/01/01 时,InvoiceDate 是 2015/01/01。当用户随后将其输入更改为无效的内容时,例如2015/1234,InvoiceDate 仍然是 2015/01/01。这是有道理的,因为 2015/1234 无法转换为 DateTime?

但是,我想检测这种情况并防止用户在输入无效数据(无法转换为 ViewModel 类型)时执行命令。我如何检测这种情况?我确定有一个简单的单行(如this.AllDataBindingsAreValid()),但我找不到它。

void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = this.AllDataBindingsAreValid(); // What's it really called?
}

【问题讨论】:

  • 您正在寻找IDataErrorInfo,如果您搜索c# binding validation,就会找到它。
  • 您可能正在寻找类似这篇文章中的答案:stackoverflow.com/questions/127477/…
  • 或者this 一个?
  • @Sinatr 确实解决了问题,但它不是问题的答案
  • @Sinatr:我不需要在这里实现自定义验证逻辑。我只想检测默认 WPF 数据绑定转换何时失败。

标签: c# wpf mvvm data-binding validation


【解决方案1】:

这是你要找的吗?

private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = IsValid(sender as DependencyObject);
}

private bool IsValid(DependencyObject obj)
{
    // The dependency object is valid if it has no errors and all
    // of its children (that are dependency objects) are error-free.
    return !Validation.GetHasError(obj) &&
    LogicalTreeHelper.GetChildren(obj)
    .OfType<DependencyObject>()
    .All(IsValid);
}

this 帖子 .

【讨论】:

  • 谢谢,但我认为这仅在绑定中设置了 ValidationRule 时才有效。不过我明天试试。
  • 除了直接复制答案,您还可以关闭为重复。
猜你喜欢
  • 1970-01-01
  • 2011-12-16
  • 2011-01-15
  • 2015-09-23
  • 2013-12-13
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
相关资源
最近更新 更多