GroupBox:根据文本长度调整大小 [英] GroupBox: Adjust size according to text length

查看:36
本文介绍了GroupBox:根据文本长度调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以让 GroupBox 根据 Text 中字符串的长度自动调整其宽度 属性?

Is there an easy way to have a GroupBox auto resize its width depending on the length of the string in the Text property?

假设我在 Text = "Text1" 时手动调整宽度(在 Design Mode 中)然后,当程序运行时,我将其更新为 Text = "This is the new text!" 我希望宽度自动扩展而不是换行到下一行.

Say I fit the width by hand (in Design Mode) when the Text = "Text1" then, when the program is running, I update it to Text = "This is the new text!" I would like the width to auto expand instead of wrapping over to the next line.

谢谢!

推荐答案

您需要使用 Graphics.MeasureString 方法

这里是一个简单的例子,提示,宽度取决于字体的大小而不是你的 GroupBox 属性的字体大小.

Here the simple example, hint, the width is depending of the size of the font not the font-size of your GroupBox property.

SizeF stringSize = new SizeF();
private void groupBox1_Paint(object sender, PaintEventArgs e)
{
    string measureString = "this is your text";
    Font stringFont = new Font("Arial", 17);

    // Measure string.
    stringSize = e.Graphics.MeasureString(measureString, stringFont);
}

private void button1_Click(object sender, EventArgs e)
{
    groupBox1.Text = "this is your text";
    groupBox1.Width = (int)stringSize.Width;
}

希望能帮到你.

这篇关于GroupBox:根据文本长度调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆