右键单击菜单项并显示选项

时间:2011-09-26 16:00:46

标签: c# wpf menuitem right-click contextmenu

我有菜单ServerList,我正在使用C#代码动态添加menuItems。它从文件中读取服务器列表并填充菜单项。我为每个服务器添加了右键单击选项。编辑&删除。

这一切都很好。问题是如何在单击“编辑/检测”时读取实际的服务器名称。

这是代码

       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();            
    }      

2 个答案:

答案 0 :(得分:3)

对于此用途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;
 }  

干杯。

答案 1 :(得分:0)

默认情况下,MenuItem的标头使用TextBlock显示内容。因此,在这种情况下,您需要将Header转换为TextBox,然后查看Text属性。

例如,

void item_Click(object sender, RoutedEventArgs e){
    string servername =  ((sender as MenuItem).Header as TextBlock).Text;
}