WPF:你怎么能在运行时添加一个新的菜单项添加到菜单? [英] WPF: How can you add a new menuitem to a menu at runtime?

查看:741
本文介绍了WPF:你怎么能在运行时添加一个新的菜单项添加到菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜单一个简单的WPF应用程序。我需要在运行时动态添加菜单项。当我简单地创建一个新的菜单项,并把它添加到它的父菜单项,它不会在菜单中显示,无论是否UpdateLayout请叫。



要发生什么事?让一个菜单,在运行时动态添加额外的项目



请注意:下面的代码不能正常工作

 菜单项MI =新菜单项(); 
mi.Header =项中增加;
mi.Visibility = Visibility.Visible;
// addTest是存在于定义的菜单
addTest.Items.Add(英里)的形式一个菜单项;
addTest.UpdateLayout();



目前,默认的菜单项目在XAML文件中定义。我想添加额外的菜单项到这个菜单和它现有的菜单项。然而,按照规定,上面的代码什么也不做。


解决方案

  //添加到主菜单
菜单项newMenuItem1 =新菜单项();
newMenuItem1.Header =测试123;
this.MainMenu.Items.Add(newMenuItem1);

//加入一个子项
菜单项newMenuItem2 =新菜单项();
菜单项newExistMenuItem =(菜单项)this.MainMenu.Items [0];
newMenuItem2.Header =测试456;
newExistMenuItem.Items.Add(newMenuItem2);


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.

解决方案

//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);

这篇关于WPF:你怎么能在运行时添加一个新的菜单项添加到菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆