控件动态创建与删除
private void Button_Add_Click(object sender, System.Windows.RoutedEventArgs e)
{
Button btn = new Button();
//btn.Name = "newButton";//这样设置则注册名字可为:canvas.RegisterName(btn.Name, btn);
btn.Width = 100;
btn.Height= 50;
canvas.Children.Add(btn);
canvas.RegisterName("newButton", btn);//注册名字,以便以后使用
}
private void Button_Remove_Click(object sender, RoutedEventArgs e)
{
Button btn = canvas.FindName("newButton") as Button;//找到刚新添加的按钮
if (btn != null)//判断是否找到,以免在未添加前就误点了
{
canvas.Children.Remove(btn);//移除对应按钮控件
canvas.UnregisterName("newButton");//还需要把对用的名字注销掉,否则再次点击Button_Add会报错
}
}
RegisterName中的第一个重载不能为“111”之类的可强制转换为int的string。