自动换行在Windows窗体标签窗体、换行、标签、Windows

2023-09-02 01:21:05 作者:不哭不闹失心人

我们如何能够得到自动换行功能在 Windows窗体?

How can we get word wrap functionality for a label in Windows Forms?

余放置一个标签在一个面板和加入一些文本来动态标记。但它超过面板的长度。我该如何解决这个问题?

I placed a label in a panel and added some text to label dynamically. But it exceeds the panel length. How can I solve this?

推荐答案

简单的回答:开关的关闭 AutoSize.

The quick answer: switch off AutoSize.

这里最大的问题是,标签不会自动改变其高度(仅宽)。为了得到这个权利,你将需要继承的标签,包括垂直大小调整的逻辑。

The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.

基本上你需要做的OnPaint是什么:

Basically what you need to do in OnPaint is:

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

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

You will also need to set the ResizeRedraw style flag in the constructor.