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 artcile but unable to attach event to my sub menu items.
views:
3024answers:
3
+9
A:
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 DoSometing = 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" />
Guffa
2009-03-02 06:10:09
Having the _static_ class to hold the RoutedUICommands was the key for me. (If they were in my Window1 class, the XAML couldn't find them.) Thanks!
ewall
2009-12-29 22:11:39
A:
the 'h' is missing in public static readonly RoutedUICommand DoSometing
and didn't work for me until i fixed it. The code is very helpful, thanks a lot! :)
p_queensgod
2010-06-15 15:31:01
+1
A:
Instead of defining them in a static class, you might as well declare the commands directly in XAML. Example (adapted from Guffas nice example):
<Window.Resources>
<RoutedUICommand x:Key="DoSomethingCommand" Text="Do Something" />
<RoutedUICommand x:Key="DoSomethingElseCommand" Text="Do Something Else" />
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource DoSomethingCommand}" Executed="CommandBinding_DoSomething" />
<CommandBinding Command="{StaticResource DoSomethingElseCommand}" Executed="CommandBinding_DoSomethingElse" />
</Window.CommandBindings>
...
<MenuItem Name="Menu_DoSomething" Header="Do Something" Command="{StaticResource DoSomethingCommand}" />
Heinzi
2010-06-15 15:38:57