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


当前回答

根据@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;这里我们关心顶部和底部的填充。

其他回答

把标签放在面板里 处理面板的ClientSizeChanged事件,使 标签填充空间: Panel2_ClientSizeChanged(对象发送器,EventArgs e) { label1。MaximumSize =新大小((发送方作为控件). clientsize . Size。宽度- label1。离开,10000); } 将标签的自动大小设置为true 将标签“Dock”设置为“Fill”

除了第2步,其他步骤通常都在设计器窗口中完成。

不确定它是否适合所有用例,但我经常使用一个简单的技巧来获得包装行为: 把你的标签与AutoSize=false在1x1 TableLayoutPanel,这将照顾标签的大小。

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

我必须找到一个快速的解决方案,所以我只是使用了一个具有这些属性的文本框:

var myLabel = new TextBox
                    {
                        Text = "xxx xxx xxx",
                        WordWrap = true,
                        AutoSize = false,
                        Enabled = false,
                        Size = new Size(60, 30),
                        BorderStyle = BorderStyle.None,
                        Multiline =  true,
                        BackColor =  container.BackColor
                    };

这个问题的简单答案是改变Label的DOCK属性。默认为“NONE”。