TableLayoutPanel的行高不正确

时间:2016-04-09 11:15:16

标签: c# winforms autosize tablelayoutpanel

我在每个单元格中都有自动调整大小的2x2表格布局和长自动调整大小的标签。 此布局采用其他表格布局,没有自动调整大小的单元格。 重现问题的最小项目:

using System;
using System.Windows.Forms;

namespace TestForms {
    static class Program {
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new TestForm());
        }
    }

    class TestForm : Form {
        public TestForm() {
            var childPanel = new TableLayoutPanel();
            var label8 = new Label();
            var label9 = new Label();
            var label10 = new Label();
            var label7 = new Label();
            var rootPanel = new TableLayoutPanel();

            childPanel.AutoSize = true;
            childPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            childPanel.BackColor = System.Drawing.Color.Silver;
            childPanel.ColumnCount = 2;
            childPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
            childPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
            childPanel.Controls.Add(label8, 1, 0);
            childPanel.Controls.Add(label9, 0, 1);
            childPanel.Controls.Add(label10, 1, 1);
            childPanel.Controls.Add(label7, 0, 0);
            childPanel.Dock = DockStyle.Top;
            childPanel.RowCount = 2;
            childPanel.RowStyles.Add(new RowStyle());
            childPanel.RowStyles.Add(new RowStyle());

            label8.AutoSize = true;
            label8.Text = "2ggggggggggggggggg";

            label9.AutoSize = true;
            label9.Text = "label9";

            label10.AutoSize = true;
            label10.Text = "label10";

            label7.AutoSize = true;
            label7.Text = "label7";

            rootPanel.ColumnCount = 1;
            rootPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
            rootPanel.Controls.Add(childPanel, 0, 0);
            rootPanel.Dock = DockStyle.Fill;
            rootPanel.RowCount = 1;
            rootPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));

            ClientSize = new System.Drawing.Size(205, 197);
            Controls.Add(rootPanel);
        }
    }
}

我得到以下结果:

Screenshot

为什么最后一行的高度错误?有解决方法吗?

1 个答案:

答案 0 :(得分:0)

有趣的是,似乎你遇到了一些错误,因为如果某些标签AutoSizefalse,或者制作第一列样式SizeType.AutoSize等,它就不会发生。

您可以使用以下解决方法。它很难看,但这是我找到的唯一方法。我们的想法是添加包含假Label的不可见行,AutoSize设置为false。例如,在设置正常布局后,添加以下行:

childPanel.RowCount++;
childPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 0));
childPanel.Controls.Add(new Label { AutoSize = false }, 0, childPanel.RowCount - 1);