【问题标题】:WPF - Add buttons in chess-like layoutWPF - 在类似国际象棋的布局中添加按钮
【发布时间】: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.RowGrid.Column 附加属性。 Grids 的互联网上有大量示例。我建议您通过几个示例来了解 WPF 以及它应该如何工作。

标签: c# wpf


【解决方案1】:

内容控件为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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      相关资源
      最近更新 更多