如何检索以编程方式创建的控件的名称
本文关键字:创建 方式 控件 编程 何检索 检索 | 更新日期: 2023-09-27 18:27:37
在一个可以通过编程创建一系列按钮的应用程序中,一旦我单击其上下文菜单,我如何检索其中一个按钮的名称?这是一段代码:
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;
..
}
但它总是给出一个空字符串。你能告诉我哪里出了错吗?感谢
在您的代码中,您将sender.Parent
强制转换为ContextMenu
。因此您知道您正在操作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;
..
}