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


当前回答

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 = True MaximumSize =(宽度,高度)其中宽度=你想要标签的最大尺寸和高度=你想要它包装多少像素

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

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

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

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

测试和工作。

我有一个标签,自动包装和增长到任何大小在右停靠的自动大小面板,其宽度是由其他内容设置。

标签(在tablelayoutpanel) Autosize = True。

tableelayoutpanel(在面板)Autosize = True, AutoSizeMode = GrowAndShrink, Dock =底部,一列SizeType = 100%,一行SizeType = 100%。

面板(右停靠形式)AutoSize = True, AutoSizeMode = GrowAndShrink, Dock =右。

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

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
                    };

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