在运行时添加 WPF 控件
我编写了一个 WPF UserControl,并希望在运行时在单击按钮时将其中一个或多个添加到我的窗口中.我该怎么做?
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?
进一步规范我想将用户控件添加到画布,并放在绝对位置.画布是我家地板的绘图,每个用户控件都有属性来指示它在房子中的位置.所以我希望所有控件都位于画布上的正确位置.
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.
我在想这样的事情
var light = new LightUserControl(2);
HouseCanvas.Children.Add(light); // this should be positioned in a specific place
将控件添加到 Canvas 后,您需要使用 Canvas.Top 和 Canvas.Left 附加属性指定顶部和左侧坐标,如下所示.
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);