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

后端 未结 5 601
天命终不由人
天命终不由人 2020-12-09 03:44

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

5条回答
  •  無奈伤痛
    2020-12-09 04:04

    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:

    
      
    
    

    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
    }
    

提交回复
热议问题