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


当前回答

在我的案例中(面板上的标签),我设置标签。AutoSize = false和标签。停靠=填充。 标签文本自动自动换行。

其他回答

根据@hypo的回答有更好的答案吗

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing)
            return;
        try {
            mGrowing = true;
            int width = this.Parent == null ? this.Width : this.Parent.Width;

            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height + Padding.Bottom + Padding.Top;
        } 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();
    }
}

Int width = this。Parent == null ?这一点。宽度:this.Parent.Width;这允许你使用自动增长标签时停靠到一个父,例如一个面板。

这一点。高度= sz。高度+填充。Bottom + Padding.Top;这里我们关心顶部和底部的填充。

从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();
    }
}

简单的回答是:关闭自动大小设置。

这里的大问题是标签不会自动改变它的高度(只改变宽度)。要做到这一点,你需要子类化标签,并包括垂直调整大小逻辑。

基本上你需要在OnPaint中做的是:

测量文本高度(Graphics.MeasureString)。 如果标签高度不等于文本的高度,则设置高度并返回。 绘制文本。

您还需要在构造函数中设置ResizeRedraw样式标志。

如果需要保持按钮尺寸不变:

myButton.Text = "word\r\nwrapped"

没有自动抓取属性,但可以通过编程来动态调整大小。这里有一个解决方案:

选择标签的属性 AutoSize = True MaximumSize =(宽度,高度)其中宽度=你想要标签的最大尺寸和高度=你想要它包装多少像素