开发者

Resize Panel according to Label size

开发者 https://www.devze.com 2023-02-05 08:08 出处:网络
I have a Panel with a Label inside. Sometimes, the Label is very long 开发者_高级运维and the panel must be resized.

I have a Panel with a Label inside.

Sometimes, the Label is very long 开发者_高级运维and the panel must be resized.

I have set the Autosize property to true for both controls, but ....

Can you help me please ?


You also must set AutoSize to true for the containing containers as well, up to the window.

My last attempt in doing so involved quite a bit of redesigning the form with TableLayoutPanel and the like since Dock/Anchor and AutoSize don't seem to mix well.


I have set the Autosize property to true for both controls, but ....

I can tell from the "but" what you are asking for. That's the AutoEllipsis property of the Label. Set it to true and set the MaximumSize property so the label cannot get bigger than its container. The user will see ... so she'll realize the text is truncated. She'll hover the mouse over the label to get a tooltip with the full text.

Letting everything grow to accommodate a label is drastically impractical. You typically can manipulate MaximumSize to let it grow vertically for a while, up to a point.


I encountered a similar problem, and here is a code for you. Assuming your Panel is anchored to the form (top,left,bottom,right), it is the form that needs to be resized, not the Panel.

    public static void FitPanel(Panel pnl)
    {
        int maxright = 0;
        int maxbottom = 0;
        foreach (Control ctl in pnl.Controls)
        {
            maxright = (ctl.Right > maxright ? ctl.Right : maxright);
            maxbottom = (ctl.Bottom > maxbottom ? ctl.Bottom : maxbottom);
        }
        int deltabottom = pnl.Bottom - (pnl.Top + maxbottom);
        int deltaright = pnl.Right - (pnl.Left + maxright);
        Form frm = pnl.FindForm();
        frm.SuspendLayout();
        frm.Height = frm.Height - deltabottom;
        frm.Width = frm.Width - deltaright;
        frm.ResumeLayout();
    }
0

精彩评论

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

关注公众号