WPF - 在类似国际象棋的布局中添加按钮
本文关键字:布局 添加 按钮 国际象棋 WPF | 更新日期: 2023-09-27 18:36:01
我想在按下按钮时将按钮添加到我的 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;
}
但这给了我一个错误,即我无法在"内容控件"中添加多个控件;这里的错误是什么?
内容控制是StackPanel, Grid, Canvas
等。您需要将所有控件放在内容控件内,因为Window
或UserControl
只能有一个子控件。
Xaml:
<StackPanel>
<Button/>
<Button/>
</StackPanel>
在您的情况下,c# 代码应如下所示:
StackPanel yourSP = new StackPanel(); // Creates a new content control.
Button button1 = new Button; // Creates buttons.
Button button2 = new Button;
this.AddChild(yourSP); // Adds StackPanel to your Window/UserControl
yourSP.Children.Add(button1); // Adds buttons to content control.
yourSP.Children.Add(button2);
它会创建一个新StackPanel
,这是一个内容控件,并在您Buttons
添加到StackPanel
之后将其作为子项添加到您的Window/UserControl
。
有关内容控制的更多信息,请参阅此处。
在我看来,完成您想要的最简单方法是使用 UniformGrid
.下面的代码未经测试,但它应该看起来像这样:
const int squareSize = 8;
var grid = new UniformGrid { Rows = squareSize, Columns = squareSize };
for (int y = 0; y < squareSize; y++)
{
for (int x = 0; x < squareSize; x++)
{
var btn = new Button { Height = 32, Width = 32 };
btn.Click += field_Click;
grid.Children.Add(btn);
fields[x, y] = btn;
}
}
this.AddChild(grid);