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


当前回答

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;

其他回答

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

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

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

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

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

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

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

如果事先要在标签中输入文本,则可以这样做。

对于设计师来说, 右键单击标签并单击属性。 在“属性”中搜索文本选项卡。 单击选项卡,然后单击旁边的箭头按钮。 上面会弹出一个对话框。 您可以在弹出框中按enter键添加行和在记事本中键入! (按enter键,你想包装标签文本)

使用System.Windows.Forms.LinkLabel代替Label,并设置属性LinkArea如下所示。

myLabel.LinkArea = new LinkArea(0, 0);