当前,我可以获得正确数量的列和行,并将按钮添加到正确的位置。
我遇到的问题是按钮的缩放。我已经尝试过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;
}
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;
但是,这将产生以下结果:
如您所见,每个按钮的宽度和高度似乎仅从第二列和第二行开始才有意义。我该怎么做才能使每个按钮的大小相同?
答案 0 :(得分:1)
我已通过清除ColumnStyles
和RowStyles
并为每一行和每一列添加新样式来解决此问题。每个样式的SizeType
设置为Percent
,并计算宽度/高度。
我已将testArr
替换为功能所在的集合sortedContainers
。
// above code hasn't changed
Single percHeight = ((Single)1 / (Single)tableLayoutPanel_TopView.RowStyles.Count) * 100;
Single percWidth = ((Single)1 / (Single)tableLayoutPanel_TopView.ColumnStyles.Count) * 100;
tableLayoutPanel_TopView.ColumnStyles.Clear();
tableLayoutPanel_TopView.RowStyles.Clear();
for (int x = 0; x < sortedContainers.Width; x++)
{
tableLayoutPanel_TopView.ColumnStyles.Add(new ColumnStyle
{
SizeType = SizeType.Percent,
Width = percWidth
});
}
for (int y = 0; y < sortedContainers.Length; y++)
{
tableLayoutPanel_TopView.RowStyles.Add(new RowStyle
{
SizeType = SizeType.Percent,
Height = percHeight
});
}