问题
I have a custom usercontrol which does the work of my app.
I need to have a variable number of my usercontrols on my form at once, the number is known at runtime.
I want each one to be full client width, and all controls to fill the window, equal size... eg. if there are two, then each are half the client height - if three, then each are one third of the client height.
And the layout should resize as the main window resizes. I don't want the user to be able to resize the controls other than by resizing the main window (so a split container is out)
I've tried to use the TableLayoutPanel to do this but when I set the GrowStyle property to TableLayoutPanelGrowStyle.AddRows, and add my controls, the number of rows doesn't change.
Surely this layout scheme isn't hard to achieve? I can't seem to figure it out?
thanks
回答1:
It the layout is simple to calculate then it gets to be pretty hard to make TLP pay off. Which is a control that works very well in the designer but is pretty awkward when you have an unpredictable number of controls.
This will work fine as well, a lot less code and one less control to slow your UI down:
protected override void OnResize(EventArgs e) {
for (int ix = 0; ix < Controls.Count; ++ix) {
int y1 = this.ClientSize.Height * ix / Controls.Count;
int y2 = this.ClientSize.Height * (ix + 1) / Controls.Count;
Controls[ix].Bounds = new Rectangle(0, y1, this.ClientSize.Width, y2-y1);
}
base.OnResize(e);
}
protected override void OnLoad(EventArgs e) {
OnResize(e);
base.OnLoad(e);
}
回答2:
Yes, you can use Table layout panel. in that each row height and width should be in percentage with equal to all rows. then it will work.
回答3:
Here is a little example using buttons to fill each cell of the TableLayoutPanel that is configured with 1 cell and a Row.SizeType = Percentage:
private int buttonCount = 0;
void button1_Click(object sender, EventArgs e) {
Button b = new Button() { Text = "Button #" + (++buttonCount).ToString() };
b.Dock = DockStyle.Fill;
if (buttonCount == 1) {
tlp.Controls.Add(b, 0, 0);
} else {
tlp.RowStyles.Add(new RowStyle() { SizeType = SizeType.Percent });
tlp.Controls.Add(b, 0, tlp.RowCount);
tlp.RowCount++;
}
Single percHeight = ((Single)1 / (Single)tlp.RowStyles.Count) * 100;
foreach (RowStyle rs in tlp.RowStyles) {
rs.Height = percHeight;
}
}
Every time you add a button (or a usercontrol) you recalculate the percentage height of each row.
来源:https://stackoverflow.com/questions/16303805/windows-forms-dynamic-layout