1

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?

Em1
  • 1,077
  • 18
  • 38
  • 1
    by default it is the responsibility of the command executor to verify id the command can be executed. – pushpraj Aug 27 '14 at 12:01

2 Answers2

2

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);
toadflakz
  • 7,764
  • 1
  • 27
  • 40
1

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.

Ivan Zub
  • 785
  • 3
  • 13