2

I am struggling to see what the benefits are of using Custom RoutedCommands in WPF over a standard event.

Suppose I have a custom RoutedCommand declared in a static class like so:

public static readonly RoutedCommand Foo = new RoutedCommand();

And to hook it up to a UIElement I would do this:

CommandBindings.Add(new CommandBinding(Commands.Foo, new ExecutedRoutedEventHandler((x, y) => {

            MessageBox.Show("Something Happend");

        })));

Ok, normally in a more clean way, but my first question is-How does the routed command track that this particular UI Element has a CommandBinding against it? Is the routedcommand tracking through the entire application tree for commandbindings until it finds a UIElement with the correct routedcommand in its commandbindings list?

I've noticed something still has to fire this command, like a button

btn.Command = Commands.Foo;

My next question, what is the point of creating these routedcommands over just a standard event?

William
  • 1,837
  • 2
  • 22
  • 36

1 Answers1

2

The main benefit is that it separates the different layers of your application when using MVVM. It puts the code in the ViewModel and doesn't pollute your view. It also allows commands to Bubble up the visual tree so that container controls can handle commands of their children.

It looks to me from your example code that you aren't really using MVVM, so if you don't need the bubbling (or tunneling) features, you may not get any benefit from using commands.

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
  • 1
    The command can also tunnel (drill down), though that happens less often then bubbling up. – myermian Aug 12 '15 at 19:17
  • With bubbling the event will be handled by the youngest child first; and if not handled it will hit the next element up the tree until handled? – William Aug 12 '15 at 19:20
  • Yes, it will climb the visual tree, from child to parent (or parent to child in the case of tunneling), until it finds something that can handle the command. – Bradley Uffner Aug 12 '15 at 19:22
  • Great thanks for the answer, one last question about MVVM, the CommandBindings Collection is held by a UIElement, which of course is associated with my view, so how do I go about moving the handling logic to my viewmodel? Is it simply a case of replacing the `new ExecutedRoutedEventHandler((x, y) lambda with a method in my viewmodel? – William Aug 12 '15 at 19:31
  • The typical pattern is having a read only property of `ICommand` on the viewmodel that returns the actual command instance, then binding the `Command` of the view's element to the `Command` property of the view model. – Bradley Uffner Aug 12 '15 at 19:33
  • MVVM's "native" commands are RelayCommand/DelegateCommand. In fact, there are very rare cases, when you really need to expose RoutedCommand from view models. – Dennis Aug 12 '15 at 19:57