我有一个带菜单的简单WPF应用程序.我需要在运行时动态添加菜单项.当我只是创建一个新的菜单项,并将其添加到其父MenuItem时,无论是否调用UpdateLayout,它都不会显示在菜单中.
允许菜单在运行时动态添加其他项目必须发生什么?
注意:以下代码不起作用.
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();
目前,默认菜单项在xaml文件中定义.我想在此菜单及其现有菜单项中添加其他菜单项.但是,如上所述,上述代码什么都不做.
//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);
我已成功将菜单项添加到预定义的菜单项.在下面的代码中,LanguageMenu在xaml的设计视图中定义,然后在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 }
我知道这是一个老帖子,但我遇到了同样的问题.在我的情况下,问题是在XAML
中直接包含在一个
.一旦我把它放在
里面它开始工作.所以:
不好
很好