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

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.

11/14/2008 10:05:09 PM

Accepted Answer

//Add to main menu
MenuItem newMenuItem1 = new MenuItem();
newMenuItem1.Header = "Test 123";

//Add to a sub item
MenuItem newMenuItem2 = new MenuItem();
MenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0];
newMenuItem2.Header = "Test 456";
11/14/2008 9:47:33 PM

I have successfully added menu items to a pre-defined menu item. In the following code, the LanguageMenu is defined in design view in th xaml, and then added the sub items in C#.


<MenuItem Name="LanguageMenu" Header="_Language">
  <MenuItem Header="English" IsCheckable="True" Click="File_Language_Click"/>


// Clear the existing item(s) (this will actually remove the "English" element defined in XAML)

// Dynamically get flag images from a specified folder to use for definingthe menu items 
string[] files = Directory.GetFiles(Settings.LanguagePath, "*.png");
foreach (string imagePath in files)
  // Create the new menu item
  MenuItem item = new MenuItem();

  // Set the text of the menu item to the name of the file (removing the path and extention)
  item.Header = imagePath.Replace(Settings.LanguagePath, "").Replace(".png", "").Trim("\\".ToCharArray());
  if (File.Exists(imagePath))
    // Create image element to set as icon on the menu element
    Image icon = new Image();
    BitmapImage bmImage = new BitmapImage();
    bmImage.UriSource = new Uri(imagePath, UriKind.Absolute);
    icon.Source = bmImage;
    icon.MaxWidth = 25;
    item.Icon = icon;

  // Hook up the event handler (in this case the method File_Language_Click handles all these menu items)
  item.Click += new RoutedEventHandler(File_Language_Click); 

  // Add menu item as child to pre-defined menu item
  LanguageMenu.Items.Add(item); // Add menu item as child to pre-defined menu item

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