Search code examples
c#.netwpfrouted-commands

What is the benefit of using RoutedCommands in WPF


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?


Solution

  • 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.