Add WPF control at runtime

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);

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();
newLabel.Content = "The New Element";
Main.Children.Add(newLabel);
Grid.SetColumn(newLabel, 0);
Grid.SetRow(newLabel, 0);

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

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

You can do this in many ways.

Tags:

Wpf