问题
Is there an easy way to have a GroupBox
auto resize its width depending on the length of the string in the Text
property?
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.
Thanks!
回答1:
You need to get the width of the string using the Graphics.MeasureString Method
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;
}
I hope it will helps you.
回答2:
I believe you can set the AutoSize property to true.
来源:https://stackoverflow.com/questions/14737392/groupbox-adjust-size-according-to-text-length