我们说我有一个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?
}
答案 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帖子的信用