gpt4 book ai didi

c# - 如何检测代码中的 ViewModel 绑定(bind)错误?

转载 作者:行者123 更新时间:2023-11-30 18:24:39 27 4
gpt4 key购买 nike

假设我有一个 ViewModel

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

并且这个 ViewModel 绑定(bind)到一个文本框:

<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?
}

最佳答案

这是您要找的吗?

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邮政.

关于c# - 如何检测代码中的 ViewModel 绑定(bind)错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31001335/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com