Docking a Control inside a Docked FlowLayoutPanel

2019-01-20 14:54发布

We added the property "Dock = Dockstyle.Fill" to our FlowLayoutPanel so that it resizes and fills its parent control. Now we added two GroupBoxes to the FlowLayoutPanel. These should have the same width as the Panel, but when we use "Dock = Dockstyle.Top" it doesn't work.

Problem is, we tried to set the width with "Width = Parent.Width". That would work but with our approach, to create the UI via a XML File, at the moment we want to set the width, the GroupBoxes doesn't have a parent yet. It will be added to the FlowLayoutPanel later.

By the way we also added the "FlowDirection = TopDown" to the FlowLayoutPanel, but if the GroupBoxes become smaller it places them side by side instead of TopDown.

So we are looking for a way to get all controls beneath each other and to get all GroupBoxes the same width as the FlowLayoutPanel.

Thanks for every help,

Dominic

1条回答
仙女界的扛把子
2楼-- · 2019-01-20 15:14

In the case that you described, when you only want top-down flow, you can simply use Panel instead of FlowLayoutPanel. Set the panel AutoScroll to true, and its Dock to Fill and then add group boxes to panel and set Dock property of them to Top.

Note:
For future uses of FlowLayoutPanel you may find this helpful:

How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control

This is the general rule for anchoring and docking in the FlowLayoutPanel control:

For vertical flow directions, the FlowLayoutPanel control calculates the width of an implied column from the widest child control in the column. All other controls in this column with Anchor or Dock properties are aligned or stretched to fit this implied column. The behavior works in a similar way for horizontal flow directions. The FlowLayoutPanel control calculates the height of an implied row from the tallest child control in the row, and all docked or anchored child controls in this row are aligned or sized to fit the implied row.

Example:

For example following, if you run following code:

for (int i = 0; i < 5; i++)
{
    var control = new GroupBox()
    {
        Text = i.ToString(),
        Dock = DockStyle.Top,
        Height = 40
    };

    this.panel1.Controls.Add(control);
    //To reverse the order, uncomment following line
    //control.BringToFront();
}

The result will be:

4
3
2 
1
0

You can reverse the order of items, by uncommenting the comment code.

查看更多
登录 后发表回答