views:

86

answers:

1

The WPF CommandManager allows you to do the following (pseudo-ish-code):

<Button Name="SomeButton" Command="{Binding Path=ViewModelCommand}"/>

And in the code-behind:

private void InitCommandEvents()
{
    CommandManager.AddExecutedEventHandler(this.SomeButton, SomeEventHandler);
}

The SomeEventHandler never gets called.

To me this didn't seem like something very wrong to try and do, but if you consider what happens inside CommandManager.AddExecutedEventHandler, it makes sense why it doesn't. Add to that the fact that the documentation clearly states that the CommandManager only works with RoutedCommands.

Nonetheless, this had me very frustrated for a while and led me to this question:

What would you suggest is the best workaround for the fact that the CommandManager does not support custom ICommands? Especially if you want to add behavior around the execution of a command?

For now, I fire the command manually in code behind from the button click event.

A: 

I generally just subclass RoutedCommand and re-use its functionality instead of implementing an ICommand from scratch. Then it works well with CommandManager, etc, and everyone is happy.

On the other hand, if you do implement an ICommand from scratch, it seems to me that there's no need of CommandManager.AddExecutedEventHandler: Your custom ICommand can easily expose its own way of registering for notifications when the command executes. In fact, most custom ICommand implementations do this as the primary way of handling command execution.

Either way it doesn't seem you would ever need both custom ICommand functionality and CommandManager support at the same time.

Ray Burns
Yes I also considered subclassing RoutedCommand. Thanks for your advice.
Andre Luus