问题
I hope I asked the right question, but here's my situation. I have a TreeViewItem
that I'm implementing. Inside it I set/add various properties, one of them being a ContextMenu
. All I want to do is add MenuItems
to the ContextMenu
without passing to functions and such.
Here's how I implement my TreeViewItem
with 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
}
};
Thanks a lot!
回答1:
Sonhja answer is correct. Providing a example for your case.
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);
回答2:
For that purpose in WPF
I did this:
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;
You can set it to any element that supports so.
EDIT: I'm writing it by memory, sorry if it's not exact. But more or less that's the idea.
来源:https://stackoverflow.com/questions/18080363/is-it-possible-to-add-menu-items-to-a-context-menu-during-implementation