如何获得一个标签的换行功能的文本,这是越界?
当前回答
事实上,公认的答案是不必要的复杂。
如果您将标签设置为“自动大小”,它将随着您放入的任何文本而自动增长。(这包括垂直增长。)
如果你想让它以特定的宽度换行,你可以设置MaximumSize属性。
myLabel.MaximumSize = new Size(100, 0);
myLabel.AutoSize = true;
测试和工作。
其他回答
根据@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;这里我们关心顶部和底部的填充。
在我的案例中(面板上的标签),我设置标签。AutoSize = false和标签。停靠=填充。 标签文本自动自动换行。
从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);
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本