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

后端 未结 3 1544
悲哀的现实
悲哀的现实 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条回答
  •  猫巷女王i
    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;
    

提交回复
热议问题