我编写了一个WPF UserControl,并希望在单击按钮时在运行时将一个或多个添加到我的Window中。我怎么能这样做?
编辑:进一步说明 我想将usercontrols添加到Canvas,并置于绝对位置。画布是我家中楼层的图纸,每个用户控件都有属性,用于指示房屋的位置。所以我希望所有控件都放在画布上的正确位置。
我在想这样的事情
var light = new LightUserControl(2);
HouseCanvas.Children.Add(light); // this should be positioned in a specific place
答案 0 :(得分:39)
将控件添加到Canvas后,需要使用Canvas.Top和Canvas.Left附加属性指定顶部和左侧坐标,如下所示。
var light = new LightUserControl(2);
HouseCanvas.Children.Add(light);
Canvas.SetLeft(light, 20);
Canvas.SetTop(light, 20);
答案 1 :(得分:12)
如果您想将控件添加到Grid而不是Canvas,您可以通过Grid静态类指定所有Grid属性,如下所示:
Label newLabel = new Label();
label.Content = "New Element";
Main.Children.Add(newLabel);
Grid.SetColumn(newLabel, 0);
Grid.SetRow(newLabel, 0);
答案 2 :(得分:2)
将StackPanel添加到窗口并在每个按钮上单击
_stackPanel.Children.Add(new YourControl());
你可以通过多种方式做到这一点。
答案 3 :(得分:2)
我的解决方案:
for (i = 1; i <= buttoncount; i++)
{
Button mybutton = new Button();
Grid1.Children.Add(mybutton);
mybutton.Height = 100;
mybutton.Width = 100;
mybutton.Name = "button" + i;
mybutton.Content = mybutton.Name;
}
答案 4 :(得分:0)
public static void AddChild(this Visual parent, UIElement child)
{
if (InternalAddChild(parent, child))
{
return;
}
throw new NotSupportedException();
}
private static bool InternalAddChild(Visual parent, UIElement child)
{
Panel panel = parent as Panel;
if (panel != null)
{
panel.Children.Add(child);
return true;
}
for (int i = VisualTreeHelper.GetChildrenCount(parent) - 1; i != -1; i--)
{
Visual target = VisualTreeHelper.GetChild(parent, i) as Visual;
if (target != null && InternalAddChild(target, child))
{
return true;
}
}
return false;
}
答案 5 :(得分:0)
只是补充答案:
for (i = 1; i <= buttoncount; i++)
{
Button mybutton = new Button();
Grid1.Children.Add(mybutton);
mybutton.Height = 100;
mybutton.Width = 100;
mybutton.Name = "button" + i;
mybutton.Content = mybutton.Name;
mybutton.Click += button_Click;
}
private void button_Click(object sender, RoutedEventArgs e)
{
// do something
}