Right click on a menu item and show options
I have menu ServerList, I am adding the menuItems dynamically using C# code. It reads the servers list from file and populate the menu items. I have added the right click options for each server. Edit & Delete.
All this is working fine. the problem is how do I read actual server name when Edit/Detele is clicked.
Here is the code
开发者_如何学JAVA public MainWindow()
{
InitializeComponent();
LoadMenuItems();
}
//Currently static values, but reads from file. later
private void LoadMenuItems()
{
MenuItem item2 = new MenuItem();
item2.Header = "Server1";
AddContextMenu(item2);
MenuItem item3 = new MenuItem();
item3.Header = "Server2";
AddContextMenu(item3);
ActualMenu.Items.Add(item2);
ActualMenu.Items.Add(item3);
}
private void AddContextMenu(MenuItem item)
{
MenuItem item1 = new MenuItem();
item1.Header = "Edit";
item1.Click += item_Click;
MenuItem item2 = new MenuItem();
item2.Header = "Detlete";
item2.Click += item_Click;
ContextMenu menu = new ContextMenu();
menu.Items.Add(item1);
menu.Items.Add(item2);
item.ContextMenu = menu;
}
void item_Click(object sender, RoutedEventArgs e)
{
MenuItem item = sender as MenuItem;
string header = item.Header.ToString();
}
For this use PlacementTarget
.
private void AddContextMenu(MenuItem item)
{
MenuItem item1 = new MenuItem();
....
ContextMenu menu = new ContextMenu();
....
menu.PlacementTarget = item; /// 'Connects' context menu to source menu item.
item.ContextMenu = menu;
}
void item_Click(object sender, RoutedEventArgs e)
{
MenuItem item = sender as MenuItem;
string header
= ((MenuItem)((ContextMenu)((MenuItem)sender).Parent).PlacementTarget).Header;
}
Cheers.
By default, the Header of a MenuItem uses a TextBlock to display content. So, in this case you need to convert the Header to a TextBox, then look at the Text property.
For example,
void item_Click(object sender, RoutedEventArgs e){
string servername = ((sender as MenuItem).Header as TextBlock).Text;
}
精彩评论