我希望我提出正确的问题,但这是我的情况。我有TreeViewItem
我正在实施。在其中我设置/添加各种属性,其中一个是ContextMenu
。我想要做的就是将MenuItems
添加到ContextMenu
而不传递给函数等。
以下是我如何使用TreeViewItem
实施ContextMenu
:
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
}
};
非常感谢!
答案 0 :(得分:2)
为此目的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;
您可以将其设置为支持的任何元素。
编辑:我是通过记忆来写的,抱歉,如果不准确的话。但或多或少是这个想法。
答案 1 :(得分:1)
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);