如何在wpf中删除动态添加的控件

时间:2013-09-23 13:34:04

标签: c# wpf

我无法在按钮点击事件中删除动态添加的控件。让我知道如何做到这一点。

public void populateform(ArrayList list)
{
  int i = 1;
  int count = 0;

  foreach (string cartitems in list)
  {
    Label lbl = new Label();
    lbl.Name = "myLabel"+i;

    lbl.Content = cartitems.ToString();
    mystackpanel.Children.Add(lbl);
    i++;
    ++count;
    if (count % 3 == 0)
    {
      Button btndelete = new Button();
      btndelete.Content = "Delete";

      btndelete.Width = 120;
      btndelete.Height = 35;
      btndelete.Click += new RoutedEventHandler(btndelete_Click);

      mystackpanel.Children.Add(btndelete);                    
    }
  }
}

private void btndelete_Click(object sender, RoutedEventArgs e)
{
  Label lbl2 = (Label)this.mystackpanel.FindName("myLabel2");
  this.mystackpanel.Children.Remove(lbl2);               
}

2 个答案:

答案 0 :(得分:6)

来自FindName的备注部分:

  

FindName在当前元素的名称范围内运行。有关详细信息,请参阅WPF XAML Namescopes

简而言之,您必须致电RegisterName才能使FindName适用于动态创建的元素。

lbl.Name = "myLabel" + i;
lbl.Content = cartitems;
mystackpanel.Children.Add(lbl);
mystackpanel.RegisterName(lbl.Name, lbl); // here

然而,如下所示,可以更容易地按名称查找元素,而不使用FindName

var element = mystackpanel.Children
    .OfType<FrameworkElement>()
    .FirstOrDefault(e => e.Name == "myLabel2")

答案 1 :(得分:4)

Label lbl = (Label)LogicalTreeHelper.FindLogicalNode(mystackpanel, "myLabelx");
mystackpanel.Children.Remove(lbl);