Reputation: 1808
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!
Upvotes: 2
Views: 1583
Reputation: 8448
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.
Upvotes: 2
Reputation: 4109
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);
Upvotes: 1