Does calling "command.Execute" implicitly call CanExecute first?

413 Views Asked by At

I just implemented a call of Execute for a Command without calling CanExecute first.

From debugging I would tell that CanExecute is called though; however, I'm not sure if this is coincidence.

I'd like to know if I can rely on the fact that CanExecute is implicitly called whenever I raise the Execute by hand, or if I should ensure calling CanExecute myself?

2

There are 2 best solutions below

0
On

You can't rely on that. CanExecute() is called when a Command is bound to a Command-enabled UI item like a Button (via the CommandManager) but checking CanExecute() in Execute() itself would be an implementation detail for a specific implementation of ICommand and is not implied.

However, it's an interesting idea and not a bad one considering how often I've had to do the following in my own code:

if (SomeCommand.CanExecute(null))
    SomeCommand.Execute(null);
0
On

No, it doesn't stop the command from execute if you just call the Execute method. If you want to do so you should use:

if(myCommand.CanExecute())
{
    myCommand.Execute(); 
}

Or if you are using that command from binding you should raise myCommand.RaiseCanExecuteChanged when changing the corresponding properties.