是否可以在实现过程中将菜单项添加到上下文菜单中
本文关键字:添加 上下文 菜单 菜单项 实现 过程中 是否 | 更新日期: 2023-09-27 18:26:33
我希望我问的问题是对的,但这是我的情况。我有一个正在实现的TreeViewItem
。我在里面设置/添加了各种属性,其中一个是ContextMenu
。我所想做的就是将MenuItems
添加到ContextMenu
中,而不传递给函数等。
以下是我如何用ContextMenu
:实现我的TreeViewItem
public static TreeViewItem Item = new TreeViewItem() //Child Node
{
ContextMenu = new ContextMenu //CONTEXT MENU
{
Background = Brushes.White,
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(1),
//**I would like to add my MENUITEMS here if possible
}
};
非常感谢!
为此,在WPF
中我做了以下操作:
TreeViewItem GreetingItem = new TreeViewItem()
{
Header = "Greetings",
ContextMenu = new ContextMenu //CONTEXT MENU
{
Background = Brushes.White,
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(1),
}
};
// Create ContextMenu
contextMenu = new ContextMenu();
contextMenu.Closing += contextMenu_Closing;
// Exit item
MenuItem menuItemExit = new MenuItem
{
Header = Cultures.Resources.Exit,
Icon= Cultures.Resources.close
};
menuItemExit.Click += (o, a) =>
{
Close();
}
// Restore item
MenuItem menuItemRestore = new MenuItem
{
Header = Cultures.Resources.Restore,
Icon= Cultures.Resources.restore1
};
menuItemRestore.Click += (o, a) =>
{
WindowState = WindowState.Normal;
};
contextMenu.Items.Add(menuItemRestore);
contextMenu.Items.Add(menuItemExit);
GreetingItem.ContextMenu = contextMenu;
你可以将它设置为任何支持它的元素。
编辑:我是凭记忆写的,如果不准确,很抱歉。但这或多或少是个想法。
Sonhja的答案是正确的。为你的案例提供一个例子。
TreeViewItem GreetingItem = new TreeViewItem()
{
Header = "Greetings",
ContextMenu = new ContextMenu //CONTEXT MENU
{
Background = Brushes.White,
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(1),
}
};
MenuItem sayGoodMorningMenu = new MenuItem() { Header = "Say Good Morning" };
sayGoodMorningMenu.Click += (o, a) =>
{
MessageBox.Show("Good Morning");
};
MenuItem sayHelloMenu = new MenuItem() { Header = "Say Hello" };
sayHelloMenu.Click += (o, a) =>
{
MessageBox.Show("Hello");
};
GreetingItem.ContextMenu.Items.Add(sayHelloMenu);
GreetingItem.ContextMenu.Items.Add(sayGoodMorningMenu);
this.treeView.Items.Add(GreetingItem);