如何获得一个标签的换行功能的文本,这是越界?


当前回答

如果你真的想要设置标签宽度独立于内容,我发现最简单的方法是:

设置autosize为true 设置你想要的最大宽度 设置最小宽度相同

现在标签的宽度是恒定的,但是它会自动调整它的高度。

然后对于动态文本,减小字体大小。如果需要,在设置标签文本的子代码中使用这个代码段:

If Me.Size.Height - (Label12.Location.Y + Label12.Height) < 20 Then
    Dim naam As String = Label12.Font.Name
    Dim size As Single = Label12.Font.SizeInPoints - 1
    Label12.Font = New Font(naam, size)
End If

其他回答

从MSDN,自动换行文本标签:

using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing) 
            return;
        try {
            mGrowing = true;
            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height;
        }
        finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

我建议将标签的AutoEllipsis属性设置为true, AutoSize设置为false。如果文本长度超过标签界限,它将在结尾添加三个点(…),并自动将完整的文本设置为工具提示。因此,用户可以通过将鼠标悬停在标签上看到完整的文本。

如果你真的想要设置标签宽度独立于内容,我发现最简单的方法是:

设置autosize为true 设置你想要的最大宽度 设置最小宽度相同

现在标签的宽度是恒定的,但是它会自动调整它的高度。

然后对于动态文本,减小字体大小。如果需要,在设置标签文本的子代码中使用这个代码段:

If Me.Size.Height - (Label12.Location.Y + Label12.Height) < 20 Then
    Dim naam As String = Label12.Font.Name
    Dim size As Single = Label12.Font.SizeInPoints - 1
    Label12.Font = New Font(naam, size)
End If

If your panel is limiting the width of your label, you can set your label’s Anchor property to Left, Right and set AutoSize to true. This is conceptually similar to listening for the Panel’s SizeChanged event and updating the label’s MaximumSize to a new Size(((Control)sender).Size.Width, 0) as suggested by a previous answer. Every side listed in the Anchor property is, well, anchored to the containing Control’s respective inner side. So listing two opposite sides in Anchor effectively sets the control’s dimension. Anchoring to Left and Right sets the Control’s Width property and Anchoring to Top and Bottom would set its Height property.

这个解决方案,作为c#:

label.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label.AutoSize = true;

我有一个标签,自动包装和增长到任何大小在右停靠的自动大小面板,其宽度是由其他内容设置。

标签(在tablelayoutpanel) Autosize = True。

tableelayoutpanel(在面板)Autosize = True, AutoSizeMode = GrowAndShrink, Dock =底部,一列SizeType = 100%,一行SizeType = 100%。

面板(右停靠形式)AutoSize = True, AutoSizeMode = GrowAndShrink, Dock =右。