在 C# 中的 TableLayoutPanel 中的面板中居中面板

Center a Panel within a Panel, which is in a TableLayoutPanel, in C#

所以基本上我有一个游戏板,由 TableLayoutPanel 表示。 TableLayoutPanel 的每个单元格代表板上的一个 space,并包含一个面板。每个 Panel 中都有一个 Label 来显示当前 space 中的内容(例如角色或建筑物),它的 BackColor 代表 space 中的地形类型(例如 Land、Water 等) .当玩家尝试移动角色时,该角色可以移动的每个可能 space 将变成 "highlighted." 然后玩家将双击其中一个突出显示的 space 以将角色移动到那里。

为了突出space,我在现有面板(已经有标签的面板)上添加了一个面板。

总结一下,TableLayoutPanel --> 面板 --> 标签,面板。

我遇到的主要问题是我无法让 "highlight-Panel" 在其父面板中居中;它总是左上角居中。我希望能够看到父面板的部分 BackColor,以便玩家更容易决定去哪里。因此,将 Dock 设置为 Fill 不是一个选项。 highlight-Panel 比父 Panel 略小,因此可以看到父 Panel 的 BackColor 的边缘。 是的,Anchor 设置为 None。

第二个问题是我无法更改任何标签的文本颜色。我试过在初始化时更改它,或者更直接地使用 "tableLayoutPanel.GetControlFromPosition(16, 4).Controls[0].ForeColor = Color.White;" 在特定位置更改它,但似乎没有任何效果。

老实说,我对超级复杂的黑客修复不感兴趣。但是,如果有一些简单的事情或我错过的事情,我将非常感谢您提供一些意见。谢谢

这是创建 TableLayoutPanel、其中的面板以及每个面板中的标签的代码:

// Create TableLayoutPanel to hold Panels
tableLayoutPanel = new TableLayoutPanel()
{
    RowCount = 1,
    ColumnCount = 1,
    AutoSize = true,
    AutoSizeMode = AutoSizeMode.GrowAndShrink,
    Location = new Point(12, 12),
    Dock = DockStyle.Fill,
    AutoScroll = true,  
};

// Add tableLayoutPanel to the form
this.Controls.Add(tableLayoutPanel);

// Reset and add rows/columns + styles
tableLayoutPanel.RowStyles.Clear();
tableLayoutPanel.ColumnStyles.Clear();

for (int i = 0; i < rows; i++)
{
    tableLayoutPanel.RowCount++;
    tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 50F));
}
tableLayoutPanel.RowCount--;

for (int j = 0; j < cols; j++)
{
    tableLayoutPanel.ColumnCount++;
    tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
}
tableLayoutPanel.ColumnCount--;

// Add Panels to TableLayoutPanel
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        // Create new Panel
        Panel space = new Panel()
        {
            BackColor = SystemColors.ActiveCaption,
            BorderStyle = BorderStyle.FixedSingle,
            Margin = new Padding(0),
            Size = new Size(45, 45)
        };

        space.MouseClick += new MouseEventHandler(clickOnSpace);

        // Create new Label
        Label info = new Label()
        {
            Size = new Size(93, 93),
            Text = "Info",
            Dock = DockStyle.Fill,
            TextAlign = ContentAlignment.MiddleCenter,
            Enabled = false,
            Font = new Font("Microsoft Sans Serif", 6),
            ForeColor = Color.White
        };

        // Add Label to Panel
        space.Controls.Add(info);

        // Add Panel to TableLayoutPanel
        tableLayoutPanel.Controls.Add(space, j, i);
    }
}

创建高亮面板的代码:

// Highlight potential positions using possibleMoves
private void Highlight(List<Tuple<int, int>> possibleMoves, int remaining)
{
    int r = 0;
    int c = 0;

    foreach (Tuple<int, int> pair in possibleMoves)
    {
        r = pair.Item1;
        c = pair.Item2;

        // If highlight-Panel doesn't already exist
        if (tableLayoutPanel.GetControlFromPosition(c, r).Controls.Count == 1)
        {
            // Create a Panel to highlight the space
            Panel highlight = new Panel()
            {
                Name = "highlight",
                Size = new Size(30, 30),
                BackColor = Color.Yellow,
                Anchor = AnchorStyles.None
            };

            highlight.MouseDoubleClick += new MouseEventHandler(doubleClickOnSpace);

            // Add highlight Panel to space Panel
            tableLayoutPanel.GetControlFromPosition(c, r).Controls.Add(highlight);
           // Bring highlight Panel to front
            tableLayoutPanel.GetControlFromPosition(c, r).Controls[1].BringToFront();
        }
    }
}

... Thus, setting Dock to Fill is not an option.

其实我觉得把Dock设置成Fill是个不错的选择!

看看这张图片。这是一个有 2 列和 2 行的 TableLayoutPanel。每个单元格包含一个 Pannel,其中包含一个 Panel,其中包含一个 Label。尽管你期望 Dock 属性 所有控件已设置为 Fill!

我告诉您第一个单元格的设置,您可以在其中看到 RedBlackWhite 颜色。

单元格包含:

  • 红色区域,Panel具有:

    BackColor 属性 设为 Red
    Margin 属性 全部设为 0
    Padding 属性 全部设为 5
    Dock 属性 设为 Fill

  • 黑色区域,Panel具有:

    BackColor 属性 设为 Black
    Margin 属性 全部设为 0
    Padding 属性 全部设为 5
    Dock 属性 设为 Fill

  • 白标,Label 具有:

    BackColor 属性 设为 White
    Margin 属性 全部设为 0
    Padding 属性 全部设为 0
    Dock 属性 设为 Fill

其他cell的结构完全一样,只是LabelBackColor和它的parent(和黑色那个一样),变成了Transparent,所以你看到最里面的PanelBackColor(像红色的)。

备注

答案完全基于将 Dock 属性 设置为 Fill 并为停靠控件设置合适的 Padding 值。但是还有另一个优雅的解决方案可以自动将控件保持在容器的中心,它基于使用具有 1 行和 1 列而不是面板的 TableLayoutPanel,然后设置 Anchor 属性 child 到 None。这样 child 将在 TableLayoutPanel 中水平和垂直居中。你会发现这个 post 关于它很有用:

所以我实际上达到了一个不那么复杂的方法。我没有在面板中使用面板,而是选择保留我的原始面板,并创建一个自定义标签,该标签具有可以更改粗细和颜色的外边框。这样我就不必跟踪太多控件,CustomLabel 会显示所需的一切。

自定义标签代码:

public class CustomLabel : Label
{
// Constructors

    // Default Constructor
    public CustomLabel() : base() { }

    public CustomLabel(bool drawBorder, int borderThickness, Color borderColor, Color textColor) : base()
    {
        if (drawBorder)
        {
            BorderThickness = borderThickness;
            BorderColor = borderColor;
        }

        Size = new Size(36, 36);
        Text = "Info";
        Anchor = (AnchorStyles.Left | AnchorStyles.Right);
        AutoSize = false;
        TextAlign = ContentAlignment.MiddleCenter;
        Enabled = false;
        Font = new Font("Microsoft Sans Serif", 6);
        ForeColor = TextColor;
        BorderStyle = BorderStyle.FixedSingle;
        Dock = DockStyle.Fill;

    }

    // Creates a border of specified thickness and color
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        if (BorderStyle == BorderStyle.FixedSingle)
        {
            int halfThickness = BorderThickness / 2;
            using (Pen p = new Pen(BorderColor, BorderThickness))
            {
                e.Graphics.DrawRectangle(p, new Rectangle(halfThickness,
                     halfThickness,
                     ClientSize.Width - BorderThickness, ClientSize.Height - BorderThickness));
            }
        }
    }

    public int BorderThickness { get; set; }
    public Color BorderColor { get; set; }
}

将 CustomLabel 添加到面板的代码:

// Add Panels to TableLayoutPanel
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        // Create new Panel
        Panel space = new Panel()
        {
            Size = new Size(45, 45),
            Dock = DockStyle.Fill,
            Margin = new Padding(0),
            ForeColor = Color.Red
        };

        space.MouseClick += new MouseEventHandler(MouseDownOnSpace);

        CustomLabel info = new CustomLabel(false, 0, Color.Empty, Color.Red);  // Create new CustomLabel
        space.Controls.Add(info);   // Add CustomLabel to Panel
        tlp.Controls.Add(space, j, i);      // Add Panel to TableLayoutPanel
    }
}

自定义标签调整代码:

((CustomLabel)tlp.GetControlFromPosition(col, row).Controls[0]).BorderThickness = 6;

((CustomLabel)tlp.GetControlFromPosition(col, row).Controls[0]).BorderColor = Color.Yellow;

tlp.GetControlFromPosition(col, row).Controls[0].Text = tlp.GetControlFromPosition(col, row).Controls[0].Text;  // Transfer space information

tlp.GetControlFromPosition(col, row).Refresh();     // Refresh Panel to show changes

这是最终结果: (如您所见,前景色仍然没有改变。)