tags:

views:

171

answers:

0

I have an app that allows the user to manipulate different types of data (images, text, whatever). When the user is working with one of these custom User Controls, I want to append a new drop down menu to the main menu. For example, in my ImageEditor User Control, I have the following xaml:

<UserControl.CommandBindings>
   <CommandBinding Command="cmds:ImageCommands.GrayscaleImage"
                  Executed="OnImageCommandGrayscaleImage"
                CanExecute="OnImageCommandIsGrayscaleImageAllowed" />
</UserControl.CommandBindings>
<UserControl.Resources>
   <MenuItem Header="_Workspace" x:Key="WorkspaceMenu">
      <MenuItem Command="cmds:ImageCommands.GrayscaleImage" />
   </MenuItem>
</UserControl.Resources>

What do I have to do to get this resource added to my main menu when this control takes focus?

(I know I can build all this in C#, but I'm largely doing this project to learn WPF and xaml. So, if there's a way to make this happen entirely within xaml, or by defining the UI in the xaml and then loading it in code, that would make me happiest.)


After some research, I've discovered the following almost works, but not quite:

MenuItem myMenu = (MenuItem)FindResource("WorkspaceMenu");
mainMenu.Items.Add(myMenu);

The menu from the resource is added to the main menu, but none of the command bindings are correct. (e.g. dropping down the menu from my example doesn't trigger OnImageCommandIsGrayscaleImageAllowed.)


More research: The ImageCommands.GrayscaleImage command gets triggered on the main menu's owner, NOT on this custom User Control. By changing the code to this:

MenuItem myMenu = (MenuItem)FindResource("WorkspaceMenu");
myMenu.CommandBindings.Add(new CommandBinding(
                                  ImageCommands.GrayscaleImage,
                                  OnImageCommandGrayscaleImage,
                                  OnImageCommandIsGrayscaleImageAllowed));
mainMenu.Items.Add(myMenu);

It all Just Works. However, I would really like to know why I have to create that CommandBinding in the code behind file, instead of the xaml.