如何检索以编程方式创建的控件的名称

时间:2013-08-14 18:03:57

标签: c# windows-phone-7 windows-phone-8

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

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

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

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

    }

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

1 个答案:

答案 0 :(得分:1)

在您的代码中,您将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;
   ..
}