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

后端 未结 3 1532
悲哀的现实
悲哀的现实 2020-12-05 12:57

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

One of these components is a Label w

相关标签:
3条回答
  • 2020-12-05 13:39

    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 讨论(0)
  • 2020-12-05 13:42

    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.

    0 讨论(0)
  • 2020-12-05 13:46

    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.

    0 讨论(0)
提交回复
热议问题