在从过程代码调用 Execute 之前,是否应该检查 ICommand 的 CanExecute 方法?
在 XAML 中使用 ICommand
时,WPF 使用 CanExecute
方法来启用或禁用与该命令关联的控件。但是,如果我从过程代码调用 Execute
该怎么办?我应该首先检查 CanExecute
以确保该命令可以执行,还是应该 Execute
为我处理此检查?
换句话说,我应该这样做:
if (someCommand.CanExecute(parameter, target))
someCommand.Execute(parameter, target);
或者只是这样:
someCommand.Execute(parameter, target);
When using ICommand
s in XAML, WPF uses the CanExecute
method to enable or disable controls associated with the command. But what if I am calling Execute
from procedural code? Should I first check CanExecute
to make sure that the command can execute, or should Execute
take care of this check for me?
In other words, should I do this:
if (someCommand.CanExecute(parameter, target))
someCommand.Execute(parameter, target);
Or just this:
someCommand.Execute(parameter, target);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
良好的风格要求您应该执行前者,首先检查 CanExecute。这将强制实施适当的分解和一致性。另外,如果您确实想要使用绑定到按钮的此命令,它将按预期工作。
Good style would dictate that you should do the former, check CanExecute first. This will enforce proper decomposition and a consistency in implementation. Also, in the event you ever do want to use this command bound to a button, it will work as expected.
您应该只调用 Execute 并让命令实现处理验证。 CanExecute主要是为UI状态绑定提供的。
除了非常简单的单线程场景之外,即使您首先调用 CanExecute,也很容易出现竞争条件,即命令有效性在 CanExecute 和 Execute 调用之间发生变化,从而导致对 CanExecute 的调用毫无意义。
You should just call Execute and let the command implementation handle validation. CanExecute is mainly provided for UI state bindings.
Except for very simple single-threaded scenarios even if you do call CanExecute first there could easily be a race condition whereby the command validity changes between the CanExecute and the Execute calls, rendering the call to CanExecute pointless.
您需要首先调用 CanExecute,没有任何内容说明实现 ICommand 的类会在其 Execute 方法中检查其 CanExecute。
You need to call CanExecute first, there's nothing that says that classes that implement ICommand check their CanExecute in their Execute method.