在运行时添加 WPF 控件 [英] Add WPF control at runtime

查看:46
本文介绍了在运行时添加 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);

这篇关于在运行时添加 WPF 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆