我应该在从程序代码调用Execute之前检查ICommand的CanExecute方法吗?

在XAML中使用ICommand ,WPF使用CanExecute方法启用或禁用与该命令关联的控件。 但是如果我从程序代码中调用Execute呢? 我应该首先检查CanExecute以确保该命令可以执行,还是Execute应该为我处理此检查?

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

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

或者就是这样:

 someCommand.Execute(parameter, target); 

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

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

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

您需要首先调用CanExecute,没有任何内容表明实现ICommand的类在其Execute方法中检查其CanExecute。