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

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

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

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

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

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

public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); int numGroupBoxes = 4; for (int groupBoxIndex=0; groupBoxIndex { 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); } } } } 

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

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

您声明“我不知道面板中将有多少控件”。 在设计时FlowLayoutPanel中是否有任何控件? 如果你不这样做,这听起来像预期的行为。 Panel没有任何东西,因此它所需的大小为零,因此GroupBox的所需大小为零。

如果是这种情况,那么当你在运行时实际添加控件时,它们都应该有所增加。

您为groupBox设置属性Anchor:Top,Bottom,Left,Right。