我无法在按钮单击事件中删除动态添加的控件。请告诉我该如何操作。
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);
}
ItemsControl
方法更加简洁,并且可以从一开始就教授 WPF 思维方式。 - Federico Berasategui