1

在可以以编程方式创建一系列按钮的应用程序中,如何在单击其上下文菜单后检索其中一个按钮的名称?这是一段代码:

    private void addButton_Click(object sender, System.EventArgs e)
    {
       int y = (buttonIndex * 80) + 5;
       btn.Name = "btn" + buttonIndex.ToString();
       btn.Content = "button " + buttonIndex.ToString();
       btn.Width = 440;
       btn.Height = 100;
       Thickness margin = new Thickness(0, y, 0, 0);
       btn.Margin = margin;
       // .. all other properties..

       pivot1Grid.Children.Add(btn);
       buttonIndex++;
       AddContextMenuItems(btn);  
    }  

    private void AddContextMenuWithMenuItems(Button btn)
    {
       ContextMenu contextMenu = new ContextMenu();
       MenuItem menuItem1 = new MenuItem() { Header = "Edit", Tag = "Edit" };
       MenuItem menuItem2 = new MenuItem() { Header = "Remove", Tag = "Remove" };
       menuItem1.Click += new RoutedEventHandler(menuItem1_Click);
       menuItem2.Click += new RoutedEventHandler(menuItem2_Click);
       contextMenu.Items.Add(menuItem1);
       contextMenu.Items.Add(menuItem2);
       ContextMenuService.SetContextMenu(btn, contextMenu);
    } 

现在在单击事件中,我应该能够获取单击的按钮的名称(如果上下文菜单是直接在 XAML 中创建的,它可以工作):

    void menuItem1_Click(object sender, RoutedEventArgs e)
    { 
       string btnName = ((sender as MenuItem).Parent as ContextMenu).Name;
       ..

    }

但它总是给出一个空字符串。你能告诉我错误在哪里吗?谢谢

4

1 回答 1

1

在您的代码中,您正在转换sender.ParentContextMenu. 所以你知道你正在操作 ContextMenu 对象。那你为什么期望通过查询上下文菜单的名称来神奇地得到按钮的名称呢?

在您的情况下,最简单的方法是将您的信息存储在Tag上下文菜单的属性中:

private void AddContextMenuWithMenuItems(Button btn)
{
   ContextMenu contextMenu = new ContextMenu();
   MenuItem menuItem1 = new MenuItem() { Header = "Edit", Tag = "Edit" };
   MenuItem menuItem2 = new MenuItem() { Header = "Remove", Tag = "Remove" };
   menuItem1.Click += new RoutedEventHandler(menuItem1_Click);
   menuItem2.Click += new RoutedEventHandler(menuItem2_Click);
   contextMenu.Items.Add(menuItem1);
   contextMenu.Items.Add(menuItem2);

   // Store the name of the button in the Tag property of the context menu
   contextMenu.Tag = btn.Name;

   ContextMenuService.SetContextMenu(btn, contextMenu);
} 

然后,在事件处理程序中,您只需检索之前设置的值:

void menuItem1_Click(object sender, RoutedEventArgs e)
{ 
   var contextMenu = (ContextMenu)((MenuItem)sender).Parent;
   string btnName = (string)contextMenu.Tag;
   ..
}
于 2013-08-14T19:59:16.217 回答