问题
I have several panels in a windows form application, they are sorted in two columns and maximally 4 rows, so maximally 8 panels. The number of elements included in every single panel changes during the runtime, so not to waste place on monitor I set all of them to autosize. The problem is, I dont know how I can keep them placed correctly, like how to make that when the first one shrinks that the other three come up a bit so there is not too much space between them.
回答1:
Try to use the TableLayoutPanel
or the FlowLayoutPanel
(or possibly even a SplitContainer
). They all can be very useful for this kind of task. You find them in the section Containers
in the Toolbox. You can keep the right distance by setting the margins of the panels appropriately. The TableLayoutPanel
gives you different options for sizing the rows and columns (absolute or percent size or auto). Also by working with the Dock
or the Anchor
properties of the panels and controls you can attain a dynamic behavior when resizing or adding and removing controls.
You might also have to set the MinimumSize
and MaximumSize
properties of the controls.
You can add controls like this the TableLayoutPanel
int count = tableLayoutPanel1.Controls.Count;
int newColumn = count % 2;
int newRow = count / 2;
if (newRow >= tableLayoutPanel1.RowCount) {
tableLayoutPanel1.RowCount++;
// Set appropriate row style
tableLayoutPanel1.RowStyles.Add(new RowStyle { SizeType = SizeType.AutoSize });
}
var newControl = new Button { Dock = DockStyle.Fill };
tableLayoutPanel1.Controls.Add(newControl, newColumn, newRow);
来源:https://stackoverflow.com/questions/13781603/keeping-distance-between-panels-the-same