vb.net 调整动态创建的标签大小以适应其中的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14780679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:16:27  来源:igfitidea点击:

Resizing a dynamically created label to fit the text inside it?

vb.netwinforms

提问by NotQuiteThereYet

I'm creating a label dynamically, and then adding text to it dynamically (and the amount of text added to it will be different each time). So, the label needs to always be the same width as the text inside it.

我正在动态创建一个标签,然后动态地向其中添加文本(每次添加的文本量都会有所不同)。因此,标签需要始终与其中的文本具有相同的宽度。

This happens by default when creating a label in the Windows Designer. But when creating a label dynamically, it appears to be "set" at a specific width, regardless of how much text is in it (which means that it often "cuts off" some of the text).

在 Windows 设计器中创建标签时,默认情况下会发生这种情况。但是当动态创建标签时,它似乎被“设置”在特定的宽度,不管里面有多少文本(这意味着它经常“剪掉”一些文本)。

So... any idea how I can get the dynamically created label to always stay the same width as the text inside it?

所以......知道如何让动态创建的标签始终与其中的文本保持相同的宽度吗?

回答by Steven Doggart

If you want to do it manually, you can do something like this, every time you change the text:

如果你想手动完成,你可以做这样的事情,每次更改文本时:

Dim g As Graphics = Label1.CreateGraphics()
Label1.Width = CInt(g.MeasureString(Label1.Text, Label1.Font).Width)

However, it's much easier to simply set the label's AutoSizeproperty to Trueand let the label do the work for you.

但是,简单地将标签的AutoSize属性设置为True并让标签为您完成工作要容易得多。

Label1.AutoSize = True