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


当前回答

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

其他回答

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

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;

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

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

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

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

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

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

事实上,公认的答案是不必要的复杂。

如果您将标签设置为“自动大小”,它将随着您放入的任何文本而自动增长。(这包括垂直增长。)

如果你想让它以特定的宽度换行,你可以设置MaximumSize属性。

myLabel.MaximumSize = new Size(100, 0);
myLabel.AutoSize = true;

测试和工作。