我无法删除按钮单击事件中动态添加的控件。让我知道该怎么做。
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);
}
从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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句