在可以以编程方式创建一系列按钮的应用程序中,如何在单击其上下文菜单后检索其中一个按钮的名称?这是一段代码:
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;
..
}
但它总是给出一个空字符串。你能告诉我错误在哪里吗?谢谢