How do I add a custom routed command in WPF?


I have an application that contains Menu and sub menus. I have attached Appliocation Commands to some of the sub menu items such as Cut, Copy and Paste.
I also have some other menu items that do not have application commands.
How could I add a custom command binding to those sub menu items?
I have gone through this article but unable to attach event to my sub menu items.

1/17/2013 1:05:21 AM

Accepted Answer

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:


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

    <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" />

And use the bindings in a menu for example:

<MenuItem Name="Menu_DoSomething" Header="Do Something" Command="w:Command.DoSomething" />
2/13/2011 3:22:56 AM

Instead of defining them in a static class, you might as well declare the commands directly in XAML. Example (adapted from Guffas nice example):

    <RoutedUICommand x:Key="DoSomethingCommand" Text="Do Something" />
    <RoutedUICommand x:Key="DoSomethingElseCommand" Text="Do Something Else" />
    <CommandBinding Command="{StaticResource DoSomethingCommand}" Executed="CommandBinding_DoSomething" />
    <CommandBinding Command="{StaticResource DoSomethingElseCommand}" Executed="CommandBinding_DoSomethingElse" />
<MenuItem Name="Menu_DoSomething" Header="Do Something" Command="{StaticResource DoSomethingCommand}" />

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow