TableLayoutPanel运行时添加均匀自动调整大小的列

时间:2018-04-24 15:40:36

标签: c# winforms

我正在尝试使用TableLayoutPanel创建自动调整按钮网格。当我在运行时使用以下代码添加列时,它们的大小不均匀:

tableLayoutPanel.ColumnCount += 1;
for (var i = 0; i < tableLayoutPanel.RowCount; i++) {
    var button = new Button {
        Margin = Padding.Empty,
        Padding = Padding.Empty,
        Dock = DockStyle.Fill
    }
    tableLayoutPanel.Controls.Add(button);
}

包含1列的初始表格:

1col

添加第二列:

2col

添加第3列:

3col

有没有办法让色谱柱均匀自动调整,而无需手动计算尺寸?

1 个答案:

答案 0 :(得分:0)

有必要明确重置列样式:

private void RecalculateColumnStyles()
{
    var cols = tableLayoutPanel.ColumnCount;
    var pct = (float) 100 / cols;
    tableLayoutPanel.SuspendLayout();
    tableLayoutPanel.ColumnStyles.Clear();
    for (var i = 0; i < cols; i++) {
        tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, pct));
    }
    tableLayoutPanel.ResumeLayout();
}