How to dynamically add MenuItems (with a header) to a WPF menu


Staff member
<strong>[Edit #3]</strong> - to anyone reading this question: do <strong>not</strong> under any circumstance use the approach outlined in this question. <em>It is a Coding Horror</em>. I freely admit this, knowing that all programmers have worked themselves into a corner in the past, and (especially when learning a new technology) we all have been led astray by other, well-meaning developers on the interweb. Read the answer by Robert first, then read this question. Please.

<strong>[Edit #2b]</strong>

I apologize for the length of this question - there is a question in here (at the end!), but I wanted to make sure the source code was explicit. Anyway.

<strong>[Edit #2]</strong> - question title changed to more accurately reflect the... question.

<strong>[Edit]</strong> - I've updated some more of the history as to how I ended up at the design / code that I did here: <a href="" rel="noreferrer">Obligatory Blog Post</a>. If it helps clarify the question below, feel free to read it...

<strong>Original question</strong>

The application I'm working on uses Prism and WPF, with a number of modules (currently 3), one of which hosts the application menu. Originally, the menu was static with hooks into CompositeCommand / DelegateCommands, which worked great for routing button presses to the appropriate presenter. Each MenuItem used a StackPanel in its header to display the content as a combination of an image and a text label - which was the look I was going for:

&lt;Menu Height="48" Margin="5,0,5,0" Name="MainMenu" VerticalAlignment="Top" Background="Transparent"&gt;
                &lt;MenuItem Name="MenuFile" AutomationProperties.AutomationId="File"&gt;
                            &lt;Image Height="24" VerticalAlignment="Center" Source="../Resources/066.png"/&gt;
                            &lt;ContentPresenter Content="Main"/&gt;
                    &lt;MenuItem AutomationProperties.AutomationId="FileExit" Command="{x:Static local:ToolBarCommands.FileExit}"&gt;
                                &lt;Image Height="24" VerticalAlignment="Center" Source="../Resources/002.png"/&gt;
                                &lt;ContentPresenter Content="Exit"/&gt;
                &lt;MenuItem  Name="MenuHelp" AutomationProperties.AutomationId="Help" Command="{x:Static local:ToolBarCommands.Help}"&gt;
                            &lt;Image Height="24" VerticalAlignment="Center" Source="../Resources/152.png"/&gt;
                            &lt;ContentPresenter Content="Help"/&gt;

Unfortunately, the application has gotten a bit more complex and it is desireable to have other modules register themselves with the menu - hence, I've been looking at making the menu dynamic. The goal is to have other modules (through a service) be able to add commands to the menu at will - for example, Module A will add a menu item in the Toolbar module that calls a handler in Module A. There's a few excellent articles out there on this subject - the two I've looked at are <a href="" rel="noreferrer">Building a Databound WPF Menu Using a HierarchicalDataTemplate</a> and <a href="" rel="noreferrer" title="WPF Sample Series - Databound HierarchicalDataTemplate Menu Sample">WPF Sample Series - Databound HierarchicalDataTemplate Menu Sample</a>. Following the advice in the article, I have managed to make a dynamically constructed menu with no obvious data binding problems - it can create a menu with items linked backed to my presentation model, reflecting the structure of an ObservableCollection in the presentation model

Currently, my XAML looks like the following:

&lt;UserControl x:Class="Modules.ToolBar.Views.ToolBarView"
        &lt;model:ToolBarPresentationModel x:Key="modelData" /&gt;
        &lt;HierarchicalDataTemplate DataType="{x:Type model:ToolbarObject}"
                                  ItemsSource="{Binding Path=Children}"&gt;
            &lt;ContentPresenter Content="{Binding Path=Name}"
        &lt;Binding Source="{StaticResource modelData}"/&gt;
        &lt;Menu Height="48" Margin="5,0,5,0" Name="MainMenu" VerticalAlignment="Top" Background="Transparent"

The code behind for the view does the heavy lifting in the ContentPresenter_Loaded method:

   private void ContentPresenter_Loaded(object sender, System.Windows.RoutedEventArgs e)
    ContentPresenter presenter = sender as ContentPresenter;
    if (sender != null)
        DependencyObject parentObject = VisualTreeHelper.GetParent(presenter);
        bool bContinue = true;
        while (bContinue
            || parentObject == null)
            if (parentObject is MenuItem)
                bContinue = false;
                parentObject = VisualTreeHelper.GetParent(parentObject);
        var menuItem = parentObject as MenuItem;
        if (menuItem != null)
            ToolbarObject toolbarObject = menuItem.DataContext as ToolbarObject;
            StackPanel panel = new StackPanel();
            if (!String.IsNullOrEmpty(toolbarObject.ImageLocation))
                Image image = new Image();
                image.Height = 24;
                image.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                Binding sourceBinding = new Binding("ImageLocation");
                sourceBinding.Mode = BindingMode.TwoWay;
                sourceBinding.Source = toolbarObject;
                image.SetBinding(Image.SourceProperty, sourceBinding);
            ContentPresenter contentPresenter = new ContentPresenter();
            Binding contentBinding = new Binding("Name");
            contentBinding.Mode = BindingMode.TwoWay;
            contentBinding.Source = toolbarObject;
            contentPresenter.SetBinding(ContentPresenter.ContentProperty, contentBinding);
            menuItem.Header = panel;
            Binding commandBinding = new Binding("Command");
            commandBinding.Mode = BindingMode.TwoWay;
            commandBinding.Source = toolbarObject;
            menuItem.SetBinding(MenuItem.CommandProperty, commandBinding);                    

As you can see, I'm attempting to recreate the StackPanel / Image / Name combination of the original menu, just doing so in the code behind. Attempting to do this has not worked out so well - while the menu objects are certainly being created, they don't "appear" as anything other than blank, clickable objects - the StackPanel, Image, Name, etc. aren't being rendered. Interestingly enough, it also is causing the original text in the ContentPresent in the HierarchicalDataTemplate to be erased.

The question then, is there a way to set a MenuItem's Header property in the Load event such that it will display on the UserControl properly? Is the fact that the items in the header are not being displayed indicative of a DataBinding problem? If so, what would be the proper way to bind the Header to a transient object (the StackPanel that was created in the load event handler)?

I'm open to changing anything in the code above - this is all sort of prototyping along, trying to figure out the best way to handle dynamic menu creation.