开发者

How to AutoSize the height of a Label but not the width

I have a Panel that I'm creating programmatically; additionally I'm adding several components to it.

One of these components is a Label which will contain user-generated content.

I don't know how tall the la开发者_如何学JAVAbel should be, but it does have a fixed width.

How can I set the height so that it displays all the text, without changing the width?


Just use the AutoSize property, set it back to True.

Set the MaximumSize property to, say, (60, 0) so it can't grow horizontally, only vertically.


Use Graphics.MeasureString:

public SizeF MeasureString(
    string text,
    Font font,
    int width
)

The width parameter specifies the maximum value of the width component of the returned SizeF structure (Width). If the width parameter is less than the actual width of the string, the returned Width component is truncated to a value representing the maximum number of characters that will fit within the specified width. To accommodate the entire string, the returned Height component is adjusted to a value that allows displaying the string with character wrap.

In other words, this function can calculate the height of your string based on its width.


If you have a label and you want have control over the the vertical fit, you can do the following:

MyLabel.MaximumSize = new Size(MyLabel.Width, 0)
MyLabel.Height = MyLabel.PreferredHeight
MyLabel.MaximumSize = new Size(0, 0)

This is useful for example if you have a label in a container that can be resized. In that case, you can set the Anchor property so that the label is resized horizontally but not vertically, and in the resize event, you can fit the height using the method above.

To avoid the vertical fitting to be interpreted as a new resize event, you can use a boolean:

bool _inVerticalFit = false;

And in the resize event:

if (_inVerticalFit) return;
_inVerticalFit = true;
MyLabel.MaximumSize = new Size(MyLabel.Width, 0)
MyLabel.Height = MyLabel.PreferredHeight
MyLabel.MaximumSize = new Size(0, 0)
_inVerticalFit = false;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜