开发者

Resize panel to fit contained elements in windows forms

I am creating a collapsible panel element, which would essentially be a panel element with a button element and a panel element below the button. Clicking the button causes the neighboring panel to have Visible = false. I would like to resize the containing panel when the child panel is set to invisible.

I have done this manually, by setting the Size propert开发者_开发问答y to be the sum of the widths and heights of the visible elements (either the button or the button and the child panel.)

I am curious to know though if there was a way to force the resize of the containing panel without manually calling Size.

I guess I'm looking for the inverse of the property Dock=Fill, which automatically resizes elements based on the size of their containing element.

Thanks in advance.


How about doing:

panel1.Size = new Size(0, 0);
panel1.AutoSize = true;

and then instead of changing the visibility, do this:

panel1.Controls.Remove(panel2);

and when you want to bring it back:

panel1.Controls.Add(panel2);

(panel1 is the back-panel)


I just tried the answer given by ispiro. You dont need to remove and add the control. Setting Visible can work. It depends on when you perform the layout. If panel2 performs the layout before panel1, panel2 will not resize. To make it easier, use the parents PerformLayout instead.

It's used like this:

panel1.ResumeLayout(false);
panel2.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜