Search code examples
c#wpfrouted-commands

Executing WPF routed commands manually


When executing a custom RoutedUICommand manually from code-behind, like this:

MyCommands.MyCommand.Execute(parameter, target)

do I need to call the CanExecute method first or is this already done inside the Execute method?


Solution

  • Do not assume that CanExecute will get called with Execute. The interface for ICommand does not imply that it calls CanExecute when Execute is called, so if it is important to you that it only execute when CanExecute is true, simply check it yourself.

    Also, scanning the de-compiled code for RoutedUICommand, I don't see anywhere that checks CanExecute within Execute.

    It is really more of the consumer's responsibility to determine when to call Execute/CanExecute.