tags:

views:

8268

answers:

3

I've written a WPF UserControl, and want to add one or more of it to my Window at runtime when I click a button. How can I do that?

Edit: Further specification I want to add the usercontrols to a Canvas, and put in a absolute position. The canvas is a drawing of the floors in my house, and each usercontrol has properties to indicate where in the house it is positioned. So I want all the controls to be positioned in the correct position on the canvas.

I'm thinking something like this

var light = new LightUserControl(2);
HouseCanvas.Children.Add(light); // this should be positioned in a specific place
+2  A: 

Add a StackPanel to the window and on each button click,

 _stackPanel.Children.Add(new YourControl());

You can do this in many ways.

Jobi Joy
Thanks, the .Children property was the one I needed
Frode Lillerud
Please mark this response as answered.
Micah
+13  A: 

After you add the your control to the Canvas you need to specify the top and left co-ordinates using the Canvas.Top and Canvas.Left attached properties as follows.

var light = new LightUserControl(2);
HouseCanvas.Children.Add(light);
Canvas.SetLeft(light, 20);
Canvas.SetTop(light, 20);
Ian Oakes
This is perfect, thanks!
Guy Starbuck
+2  A: 

In case you want to add the control to a Grid instead of a Canvas you can specify all the Grid properties through the Grid static class as follows:

Label newLabel = new Label();
label.Content = "New Element";
Main.Children.Add(newLabel);
Grid.SetColumn(newLabel, 0);
Grid.SetRow(newLabel, 0);
Ramiro Berrelleza
This isn't necessarily what the original questioner wanted, but it was a help to me. Thanks.
hughdbrown