开发者

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

开发者 https://www.devze.com 2023-03-25 17:37 出处:网络
When using ICommands in XAML, WPF uses the CanExecute method to enable or disable controlsassociated with the command. But what if I am calling Execute from procedural code? Should I first check CanEx

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.Ca开发者_如何学JAVAnExecute(parameter, target))
    someCommand.Execute(parameter, target);

Or just this:

someCommand.Execute(parameter, target);


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号