Search code examples
c#wpf

WPF: How can you add a new menuitem to a menu at runtime?


I have a simple WPF application with a menu. I need to add menu items dynamically at runtime. When I simply create a new menu item, and add it onto its parent MenuItem, it does not display in the menu, regardless of if UpdateLayout is called.

What must happen to allow a menu to have additional items dynamically added at runtime?

Note: the following code doesn't work.

            MenuItem mi = new MenuItem();
            mi.Header = "Item to add";
            mi.Visibility = Visibility.Visible;
            //addTest is a menuitem that exists in the forms defined menu
            addTest.Items.Add(mi);
            addTest.UpdateLayout();

At the moment, the default menu items are defined in the xaml file. I want to add additional menu items onto this menu and its existing menu items. However, as stated, the above code does nothing.


Solution

  • //Add to main menu
    MenuItem newMenuItem1 = new MenuItem();
    newMenuItem1.Header = "Test 123";
    this.MainMenu.Items.Add(newMenuItem1);
    
    //Add to a sub item
    MenuItem newMenuItem2 = new MenuItem();
    MenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0];
    newMenuItem2.Header = "Test 456";
    newExistMenuItem.Items.Add(newMenuItem2);