WPF: How can you add a new menuitem to a menu at runtime?
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#.
XAML:
<MenuItem Name="LanguageMenu" Header="_Language">
<MenuItem Header="English" IsCheckable="True" Click="File_Language_Click"/>
</MenuItem>
C#:
// Clear the existing item(s) (this will actually remove the "English" element defined in XAML)
LanguageMenu.Items.Clear();
// 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.BeginInit();
bmImage.UriSource = new Uri(imagePath, UriKind.Absolute);
bmImage.EndInit();
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
}
I ran into the same problem. In my case the problem was that in the XAML the <menuitem>
was directly contained in a <toolbar>
. Once I put the <menuitem>
inside a <menu>
it started working. So:
<toolbar>
<menuitem>
</menuitem>
</toolbar>
is bad
<toolbar>
<menu>
<menuitem>
</menuitem>
</menu>
</toolbar>
is good
//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);