Should I check an ICommand's CanExecute method before calling Execute from procedural code?

ⅰ亾dé卋堺 提交于 2019-12-06 23:04:32

问题


When using ICommands 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);

回答1:


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.




回答2:


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.




回答3:


You need to call CanExecute first, there's nothing that says that classes that implement ICommand check their CanExecute in their Execute method.



来源:https://stackoverflow.com/questions/6943076/should-i-check-an-icommands-canexecute-method-before-calling-execute-from-proce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!