在从过程代码中调用Execute之前,我应该检查iccommand的CanExecute方法吗?

本文关键字:iccommand 检查 CanExecute 方法 我应该 代码 过程 调用 之前 Execute | 更新日期: 2023-09-27 18:04:35

当在XAML中使用CanExecute时,WPF使用CC_2方法来启用或禁用与该命令相关的控件。但是如果我从程序代码调用Execute呢?我应该先检查CanExecute以确保命令可以执行,还是应该检查Execute来帮我检查?

换句话说,我应该这样做吗:

if (someCommand.CanExecute(parameter, target))
    someCommand.Execute(parameter, target);

或者就这样:

someCommand.Execute(parameter, target);

在从过程代码中调用Execute之前,我应该检查iccommand的CanExecute方法吗?

好的风格会决定你应该做前者,先检查CanExecute。这将加强适当的分解和实现的一致性。此外,如果您确实想将此命令绑定到按钮上,它将按预期工作。

您应该只调用Execute并让命令实现处理验证。CanExecute主要用于UI状态绑定。

除了非常简单的单线程场景,即使你先调用CanExecute,也很容易出现竞争条件,即在CanExecute和Execute调用之间命令有效性发生变化,使得对CanExecute的调用毫无意义。

你需要先调用CanExecute,没有什么说实现ICommand的类在Execute方法中检查它们的CanExecute