c# - 如何在 TableLayoutPanel 中动态缩放控件大小
问题描述
我的目标是使用 TableLayoutPanel 拥有一个代表我的二维数组的按钮网格。
目前我可以获得正确数量的列和行,并将按钮添加到正确的位置。
我遇到的问题是按钮的缩放。我已经尝试过其他解决方案,但它们似乎不起作用。
填表
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;
但是,这会产生以下结果:
如您所见,每个按钮的宽度和高度似乎只从第二列和第二行开始才有意义。我该怎么做才能使每个按钮的大小相同?
解决方案
解决方案
我已经通过清除ColumnStyles
andRowStyles
并为每一行和每一列添加一个新样式来修复它。每种样式都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
});
}
推荐阅读
- c# - 这是什么类型的关系以及如何在 .NET Core(EFCore、FluentAPI)中实现它?
- java - 安卓。如何知道允许的块大小(蓝牙)?
- tensorflow - 如何在不结束 12 小时限制的情况下在 Google Colab 中下载 7GB 的张量流数据集?
- python-3.x - ImportError:无法从“sklearn.externals”导入名称“joblib”
- ios - 如何在原生 IOS 中调用 Method 向 Flutter 发送数据?
- perl - 在子例程中打开文件以在 Perl 中进行读/写
- asp.net-mvc - ASP.NET Core 远程验证不起作用
- python - 在遍历列表时在数据框的一行中添加多个值
- flutter - 使用切换流时,如何处理限制为 10 的 Firestore?
- python - 关于 numpy 平均值和方便平均值的问题