内部带有flowlayout面板且autosize = true的Groupbox会缩小,就像它是空的一样

sco*_*ott 11 c# groupbox autosize flowlayoutpanel

我有一个包含flowlayout面板的groupbox,flowlayout面板包含一堆控件.我将flowlayout面板设置为与父级对接.由于我不知道面板中有多少控件,我将组框autosize设置为true,autosizemode设置为增长和缩小.当我这样做时,groupbox会缩小,就像它是空的一样.我需要标题,所以我无法删除组框.任何人都知道为什么会这样吗?

Han*_*ant 6

什么都没有阻止FlowLayoutPanel缩小到零.您至少还必须将其AutoSize属性设置为True.


ugl*_*ote 5

我今天试图做同样的事情.下面是我想出的解决方案,即将FlowLayoutPanel停靠在GroupBox内部,然后使用FlowLayoutPanel的Resize和ControlAdded事件来触发调整父GroupBox的大小.

调整大小处理程序找到FlowLayoutPanel中最后一个控件的底部,并调整GroupBox的大小,并使用足够的空间来保存FlowLayoutPanel中最底层的控件.

我尝试在FlowLayoutPanel和GroupPanel上使用AutoSize = true.但不幸的是,这允许FlowLayoutPanel水平增长.

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        int numGroupBoxes = 4;

        for (int groupBoxIndex=0; groupBoxIndex<numGroupBoxes; groupBoxIndex++ )
        {
            GroupBox groupBox = new GroupBox();
            groupBox.Text = "Group " + groupBoxIndex;
            groupBox.Size = new Size(this.Width, 0);
            groupBox.Dock = DockStyle.Top;
            this.Controls.Add(groupBox);

            FlowLayoutPanel groupBoxFlowLayout = new FlowLayoutPanel();
            groupBoxFlowLayout.Dock = DockStyle.Fill;
            groupBox.Controls.Add(groupBoxFlowLayout);

            int extraSpace = 25; // the difference in height between the groupbox and the contents inside of it

            MethodInvoker resizeGroupBox = (() =>
            {
                int numControls = groupBoxFlowLayout.Controls.Count;
                if ( numControls > 0 )
                {
                    Control lastControl = groupBoxFlowLayout.Controls[numControls - 1];
                    int bottom = lastControl.Bounds.Bottom;
                    groupBox.Size = new Size(groupBox.Width, bottom + extraSpace);
                    groupBoxFlowLayout.Size = new Size(groupBoxFlowLayout.Width, bottom);
                }
            });

            groupBoxFlowLayout.Resize += ((s, e) => resizeGroupBox());
            groupBoxFlowLayout.ControlAdded += ((s, e) => resizeGroupBox());

            // Populate each flow panel with a different number of buttons
            int numButtonsInGroupBox = 3 * (groupBoxIndex+1);
            for (int buttonIndex = 0; buttonIndex < numButtonsInGroupBox; buttonIndex++)
            {
                Button button = new Button();
                button.Margin = new Padding(0, 0, 0, 0);
                string buttonText = buttonIndex.ToString();
                button.Text = buttonText;
                button.Size = new Size(0,0);
                button.AutoSize = true;
                groupBoxFlowLayout.Controls.Add(button);
            }

        }


    }

}
Run Code Online (Sandbox Code Playgroud)

以下是调整为各种不同宽度的控件的三个屏幕截图:

控件的三个屏幕大小调整为各种不同的宽度