你好!
我需要將按鈕添加到 TableLayoutPanel,并且我希望這些按鈕可以調整大小并彼此相鄰對齊,而無需填充。為了做到這一點,我正在考慮讓 TableLayoutPanel 具有自動調整大小的列,并在運行時簡單地設定大小和寬度。
然而,當我在運行時添加這些按鈕時,我得到了奇怪和意想不到的結果。我得到的結果如下:

但我希望得到的結果如下:

視覺中的表單添加了一個簡單的 TableLayoutPanel,其中列和行設定為自動大小。其余的通過以下代碼完成:
public partial class Editor : Form
{
int gridWidth = 16;
int gridHeight = 8;
public Editor(int[] size)
{
gridWidth = size[0];
gridHeight = size[1];
InitializeComponent();
}
private void Editor_Load(object sender, EventArgs e)
{
CreateButtonArray();
tableLayoutPanel1.ColumnCount = gridWidth;
tableLayoutPanel1.RowCount = gridHeight;
}
private void CreateButtonArray()
{
for (int i = 0; i < gridHeight; i )
{
for (int j = 0; j < gridWidth; j )
{
Button b = new Button();
//b.Size = new Size(50, 50);
b.Text = $"{j},{i}";
b.Click = b_Click;
tableLayoutPanel1.Controls.Add(b, j, i);
b.Anchor = (AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom);
b.Dock = DockStyle.Fill;
}
}
}
}
uj5u.com熱心網友回復:
首先,您的面板必須填寫父表格。為此,您應該將Dock屬性設定為填充。
tableLayoutPanel1.Dock = DockStyle.Fill;
然后,您必須在列之間平均分配寬度。
var width = 100f / tableLayoutPanel1.ColumnCount;
foreach (ColumnStyle columnStyle in tableLayoutPanel1.ColumnStyles)
{
columnStyle.SizeType = SizeType.Percent;
columnStyle.Width = Width;
}
最后,您必須在各行之間平均分配高度
var height = 100f / tableLayoutPanel1.RowCount;
foreach (RowStyle rowStyle in tableLayoutPanel1.RowStyles)
{
rowStyle.SizeType = SizeType.Percent;
rowStyle.Height = height;
}
在這些創建按鈕并將它們的Dock屬性設定為DockStyle.Fill.
為避免您顯示的影像失真,您必須清除面板并再次添加列和行。這是一個例子
tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.ColumnStyles.Clear();
tableLayoutPanel1.RowStyles.Clear();
tableLayoutPanel1.ColumnCount = gridWidth;
var width = 100f / gridWidth;
for (int j = 0; j < gridWidth; j )
{
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, width));
}
tableLayoutPanel1.RowCount = gridHeight;
var height = 100f / gridHeight;
for (int i = 0; i < gridHeight; i )
{
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, height));
}
for (int i = 0; i < gridHeight; i )
{
for (int j = 0; j < gridWidth; j )
{
Button b = new Button()
{
Text = $"{j},{i}"
};
b.Click = b_Click;
tableLayoutPanel1.Controls.Add(b, j, i);
b.Dock = DockStyle.Fill;
}
}
或者只是你的方法Editor_Load應該是
private void Editor_Load(object sender, EventArgs e)
{
tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.ColumnStyles.Clear();
tableLayoutPanel1.RowStyles.Clear();
tableLayoutPanel1.ColumnCount = gridWidth;
var width = 100f / gridWidth;
for (int j = 0; j < gridWidth; j )
{
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, width));
}
tableLayoutPanel1.RowCount = gridHeight;
var height = 100f / gridHeight;
for (int i = 0; i < gridHeight; i )
{
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, height));
}
CreateButtonArray();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/483101.html
上一篇:如何在C#中旋轉正多邊形
