Source: Dynamic creation and deletion of controls in WPF
Dynamically creating controls
1. Container controls. Registername ("Name", the control to register)? Registering controls
2. Container controls. FindName ("Name") as? Control type??????//Find the control and convert it to the appropriate type
Note: Only through controls. Name to set is not available through FindName to find the control, must register
dynamically deleting Controls
1. Container controls. Children.remove (Control)????????????? Remove a control
2. Container controls. Unregistername ("Name")??????????? Cancel Registration
Other settings
1. Controls. SetValue (grid.rowproperty, 0);??????????//Set the number of rows in the Grid panel of the control
?? control. SetValue (Grid.columnproperty, 1);??????? //sets the number of columns of the control in the grid panel
2.canvas.setleft ("Control name", ";?????????????????")// Set the horizontal axis of the control in the Canvas panel
? ? Canvas.settop ("Control name", ";?????????????????/.) Set the ordinate of the control in the canvas panel
eg
Add a button to the canvas when you click the Button_add button;
Remove the newly added button when you click Button_remove;
Set: Canvas's name is canvas
Code:
private void Button_Add_Click(object sender, System.Windows.RoutedEventArgs e) { Button btn = new Button(); //btn.Name = "newButton";//这里设置的Name是找不到的 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会报错 } }
Run it and you can.
Creating and removing controls dynamically in WPF