【发布时间】:2019-03-20 18:48:02
【问题描述】:
我的目标是使用 TableLayoutPanel 制作一个代表我的二维数组的按钮网格。
目前,我可以获得正确数量的列和行,并将按钮添加到正确的位置。
我遇到的问题是按钮的缩放。我已经尝试过other solutions,但它们似乎不起作用。
填表
int[,] testArr = new int[,] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
tableLayoutPanel_TopView.ColumnCount = testArr.GetLength(0);
tableLayoutPanel_TopView.RowCount = testArr.GetLength(1);
tableLayoutPanel_TopView.AutoSize = true;
for (int y = 0; y < testArr.GetLength(1); y++)
{
for (int x = 0; x < testArr.GetLength(0); x++)
{
Button btn = new Button
{
Text = x.ToString() + "." + y.ToString(),
Dock = DockStyle.Fill,
};
tableLayoutPanel_TopView.Controls.Add(btn);
}
}
Single percHeight = ((Single)1 / (Single)tableLayoutPanel_TopView.RowStyles.Count) * 100;
Single percWidth = ((Single)1 / (Single)tableLayoutPanel_TopView.ColumnStyles.Count) * 100;
foreach (ColumnStyle style in tableLayoutPanel_TopView.ColumnStyles)
{
style.SizeType = SizeType.Percent;
style.Width = percWidth;
}
foreach (RowStyle style in tableLayoutPanel_TopView.RowStyles)
{
style.SizeType = SizeType.Percent;
style.Height = percHeight;
}
TableLayoutPanel 设置
this.tableLayoutPanel_TopView.ColumnCount = 1;
this.tableLayoutPanel_TopView.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel_TopView.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel_TopView.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel_TopView.Name = "tableLayoutPanel_TopView";
this.tableLayoutPanel_TopView.RowCount = 1;
this.tableLayoutPanel_TopView.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel_TopView.Size = new System.Drawing.Size(638, 463);
this.tableLayoutPanel_TopView.TabIndex = 0;
但是,这会产生以下结果:
如您所见,每个按钮的宽度和高度似乎只从第二列和第二行开始才有意义。我该怎么做才能使每个按钮的大小相同?
【问题讨论】:
-
似乎只有第一个 Row 样式设置为
Percent,另一个设置为固定大小或较小的值。您应该在分配新值之前删除所有样式。仅使用设计器执行相同操作,并将 25% 分配给所有行和列。你会有不同的行为。不要忘记MaximumSize和MinimumSize属性。这些在这种布局中非常重要。对于 TableLayoutPanel 及其托管的控件。 -
谢谢,我清除了
ColumnStyles和RowStyles,然后为每一行和每一列添加了各自的样式。我不通过编辑器这样做的原因是因为我只知道运行时数组的大小。 -
当然。我建议使用 Designer 对其进行测试,这样问题就会出现。如果您修复了它,请发布作为答案。
标签: c# winforms tablelayoutpanel