如何使用 WPF 将文本换行到标签中?
我有一个 TextBox
和一个标签。单击按钮后,我执行以下代码:
label1.Content = textbox1.Text;
我的问题是,如何启用标签的文本换行?一行上可能显示太多文本,如果是这种情况,我希望它自动换行为多行。
I have a TextBox
and a Label. After clicking a button, I execute the following code:
label1.Content = textbox1.Text;
My question is, how do I enable text wrapping of the label? There may be too much text to display on one line, and I want it to automatically wrap to multiple lines if that is the case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
Label
控件不直接支持 WPF 中的文本换行。您应该使用TextBlock
代替。 (当然,如果您愿意,您可以将TextBlock
放在Label
控件内。)示例代码:
The
Label
control doesn't directly support text wrapping in WPF. You should use aTextBlock
instead. (Of course, you can place theTextBlock
inside of aLabel
control, if you wish.)Sample code:
我使用了以下代码。
I used the following code.
通常,您无法将
Label
替换为TextBlock
,因为您想要使用Target
属性(它将焦点设置为目标< /em> 使用键盘时进行控制,例如下面示例代码中的 ALT+C),因为这就是Label
通过TextBlock
真正提供的全部功能。但是,
Label
使用TextBlock
来呈现文本(如果将字符串放置在Content
属性中,通常就是这样);因此,您可以在Label
内添加TextBlock
的样式,如下所示:这样您就可以保留
Label
的功能,同时也可以能够对文本进行换行。Often you cannot replace a
Label
with aTextBlock
as you want to the use theTarget
property (which sets focus to the targeted control when using the keyboard e.g. ALT+C in the sample code below), as that's all aLabel
really offers over aTextBlock
.However, a
Label
uses aTextBlock
to render text (if a string is placed in theContent
property, which it typically is); therefore, you can add a style forTextBlock
inside theLabel
like so:This way you get to keep the functionality of a
Label
whilst also being able to wrap the text.您可以在标签内放置一个 TextBlock:
You can put a TextBlock inside the label:
要在标签控件中换行文本,请更改标签的模板,如下所示:
To wrap text in the label control, change the the template of label as follows:
我建议不要使用 Label 类,而是使用 TextBlock 。这允许您设置 TextWrapping适当地。
您始终可以这样做:
但是,如果所有这些“标签”都是为了显示文本,请改用
TextBlock
。Instead of using a Label class, I would recommend using a TextBlock. This allows you to set the TextWrapping appropriately.
You can always do:
However, if all this "label" is for is to display text, use a
TextBlock
instead.我们需要放置某种可以包裹文本的控件,例如文本块/文本框
We need to put some kind of control that can wrap text like textblock/textbox
尝试使用这个
try use this
我用它从 MySql 数据库检索数据:
I used this to retrieve data from MySql Database:
试试我的版本
没有必要使用 ScrollViewer 控件。
Try my version
Not necessary to use ScrollViewer control.
其他需要记住的是父容器、
等等。受影响的
需要相应调整,否则换行不起作用。Something else to keep in mind is parent containers,
<Grid/>
and what not. Impacted<ColumnDefinition/>
needs to be adjusted accordingly, or the wrapping has no effect.