使用 TableLayoutPanel 自动调整窗体的大小,该面板在其单元格中动态填充控件

本文关键字:单元格 控件 填充 动态 TableLayoutPanel 调整 窗体 使用 | 更新日期: 2023-09-27 18:37:23

我有一个表单,里面有一个TableLayoutPanel,它有1行和1列。我用控件动态填充此TableLayoutPanel。

首先,我使用以下命令创建表:

 private void generateTable(int columnCount, int rowCount)
        {
            //Clear out the existing controls, we are generating a new table layout
            tblLayout.Controls.Clear();
            //Clear out the existing row and column styles
            tblLayout.ColumnStyles.Clear();
            tblLayout.RowStyles.Clear();
            //Now we will generate the table, setting up the row and column counts first
            tblLayout.ColumnCount = columnCount;
            tblLayout.RowCount = rowCount;
            for (int x = 0; x < columnCount; x++)
            {
                //First add a column
                tblLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
                for (int y = 0; y < rowCount; y++)
                {
                    //Next, add a row.  Only do this when once, when creating the first column
                    if (x == 0)
                    {
                        tblLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                    }
                }
            }
        }

,然后在其单元格中添加控件:

tblLayout.Controls.Add(my_control, column, row);

我还创建了这个函数,以根据 TableLayoutPanel 的行数和列数调整表单大小。

private void forceSizeLocationRecalc()
        {
            this.Height = 0;
            this.Width = 0;
            int col = this.tblLayout.ColumnCount;
            int row = this.tblLayout.RowCount;
            for (int i = 0; i < row; i++)
            {
                this.Height += this.tblLayout.GetControlFromPosition(0, i).Height;
            }
            for (int i = 0; i < col; i++)
            {
                this.Width += this.tblLayout.GetControlFromPosition(i, 0).Width;
            }
        }

并在表单设置结束时调用它。

问题是,例如,如果我首先有一个 tableLayout(col=2,row=3),并且 i 传递给表格布局的情况是(col = 3,row = 1),表单的尺寸与前一个相同,所以我必须手动调整表单的大小。我希望我的表单根据列号和行号自动调整大小。

知道吗?

谢谢

使用 TableLayoutPanel 自动调整窗体的大小,该面板在其单元格中动态填充控件

假设我正确理解了您,请确保tblLayout设置了自动大小属性,然后将函数forceSizeLocationRecalc替换为以下内容:

private void forceSizeLocationRecalc()
{
     this.Width = this.tblLayout.Width;
     this.Height = this.tblLayout.Height;
}

然后,这将强制表单采用表格布局面板的大小。显然,当表更改时,您仍然需要手动调用它。

您可以在构造表格布局面板的位置添加以下内容,以防止必须这样做:

this.tblLayout.SizeChanged += delegate { this.forceSizeLocationRecalc(); };

希望对您有所帮助!

将 TableLayoutPanel 和 Form AutoSize 属性设置为 true。这意味着 TableLayoutPanel 会根据其内容的大小(正在添加的控件)自动调整大小,而窗体会根据其内容(TableLayoutPanel)自动调整大小。

如果调整大小未自动完成或看起来很跳跃,则可以使用 SuspendLayout、ResumeLayout 和 PerformLayout 方法来控制何时进行大小调整。