如何检测代码中的ViewModel绑定错误?

时间:2015-06-23 11:17:26

标签: c# wpf mvvm data-binding validation

我们说我有一个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?
}

1 个答案:

答案 0 :(得分:0)

这是你正在寻找的吗?

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帖子的信用