Transfer from http://blog.csdn.net/wushang923/article/details/6688056
Dynamically creating controls
1. Container controls. Registername ("Name", control to register)//register control
2. Container controls. FindName ("Name") as control type//Find control and convert to corresponding 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 control
2. Container controls. Unregistername ("Name")//Cancel Registration
Other settings
1. Controls. SetValue (grid.rowproperty, 0); Set the number of rows for a control in the grid panel
Control. SetValue (Grid.columnproperty, 1); Set the number of columns for a control in the grid panel
2.canvas.setleft ("Control name", 50); Set the horizontal axis of a control in the canvas panel
Canvas.settop ("Control name", 50); To set the ordinate of a 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:[CSharp] View Plain copy print? Private void button_add_click (object sender, system.windows.routedeventargs e) { button btn = new button (); //btn. name = "Newbutton";//The name set here is not found btn. width = 100; btn. height= 50; canvas. Children.add (BTN); canvas. Registername ("Newbutton", btn);//Register the name for later use } private void button_remove_click (Object sender, routedeventargs e) { Button btn = Canvas. FindName ("Newbutton") as button;//find newly added buttons if (Btn != null)//To determine whether to find, so as not to be delayed before the addition of { canvas. Children.remove (BTN);//Remove the corresponding button control canvas. Unregistername ("Newbutton");//also need to write off the name of the use, otherwise click Button_add will error } }
private void Button_add_click (object sender, System.Windows.RoutedEventArgs e)
{
Button btn = New button ();
Btn. Name = "Newbutton";//The name set here is the btn that is not found
. Width = +;
Btn. height=;
Canvas. Children.add (BTN);
Canvas. Registername ("Newbutton", btn);//Register the name for later use
}
private void Button_remove_click (object sender, RoutedEventArgs e)
{
Button btn = Canvas. FindName ("Newbutton") as button;//finds the newly added button
if (btn! = null)//Determines whether it is found, lest it be delayed before it is added
{
canvas. Children.remove (BTN);//Remove the corresponding button control
canvas. Unregistername ("Newbutton");//also need to write off the name of the use, otherwise click Button_add will be error
}
}
Run it and you can.