How do I add a custom routed command in WPF?

I use a static class that I place after the Window1 class (or whatever the window class happens to be named) where I create instances of the RoutedUICommand class:

public static class Command {

    public static readonly RoutedUICommand DoSomething = new RoutedUICommand("Do something", "DoSomething", typeof(Window1));
    public static readonly RoutedUICommand SomeOtherAction = new RoutedUICommand("Some other action", "SomeOtherAction", typeof(Window1));
    public static readonly RoutedUICommand MoreDeeds = new RoutedUICommand("More deeds", "MoreDeeeds", typeof(Window1));

}

Add a namespace in the window markup, using the namespace that the Window1 class is in:

xmlns:w="clr-namespace:NameSpaceOfTheApplication"

Now I can create bindings for the commands just as for the application commands:

<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Open" Executed="CommandBinding_Open" />
    <CommandBinding Command="ApplicationCommands.Paste" Executed="CommandBinding_Paste" />
    <CommandBinding Command="w:Command.DoSomething" Executed="CommandBinding_DoSomething" />
    <CommandBinding Command="w:Command.SomeOtherAction" Executed="CommandBinding_SomeOtherAction" />
    <CommandBinding Command="w:Command.MoreDeeds" Executed="CommandBinding_MoreDeeds" />
</Window.CommandBindings>

And use the bindings in a menu for example:

<MenuItem Name="Menu_DoSomething" Header="Do Something" Command="w:Command.DoSomething" />

Leave a Comment