WPF - 以类似国际象棋的布局添加按钮

时间:2016-02-24 20:02:59

标签: c# wpf

我想在按下按钮时将按钮添加到我的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”中添加多个控件;这里有什么错误?

2 个答案:

答案 0 :(得分:2)

内容控制为StackPanel, Grid, Canvas等。您需要将所有控件放在内容控件中,因为WindowUserControl只能有一个子控件。

的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,它是一个内容控件,并在您向Window/UserControl添加Buttons之后将其作为子项添加到StackPanel

有关内容控件,请参阅here for more information

答案 1 :(得分:1)

在我看来,实现你想要的最简单方法是使用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);