【发布时间】:2016-02-24 20:02:59
【问题描述】:
我想在按下按钮时将按钮添加到我的 WPF 窗口。我想要一个从左上角放置的 8x8 方形按钮。我试过这段代码:
int left = 20, top = 20;
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
fields[x, y] = new Button();
fields[x, y].Margin = new Thickness(left, top, 0, 0);
left += 70;
fields[x, y].Height = 32;
fields[x, y].Width = 32;
fields[x, y].Click += new RoutedEventHandler(field_Click);
fields[x, y].Name = "Field_" + x + "_" + y;
this.AddChild(fields[x, y]);
}
left = 20;
top += 70;
}
但这给了我无法在“ContentControl”处添加多个控件的错误;这里有什么错误?
【问题讨论】:
-
尝试将按钮添加到网格之类的东西上,然后执行此操作。AddChild(grid)
-
您将一个孩子添加到
this,我认为这是您的窗口。 WPF 中的 Windows 只能有一个子级。通常人们会放某种容器作为那个孩子,例如在您的情况下,Grid控件。现在Grid可以拥有无限的孩子。您将为Grid设置行和列,并将子项(按钮)分配给设置Grid.Row和Grid.Column附加属性。Grids 的互联网上有大量示例。我建议您通过几个示例来了解 WPF 以及它应该如何工作。