【发布时间】:2010-10-03 18:49:58
【问题描述】:
如何在 WPF 中的标签文本中添加换行符,如下所示?
<Label>Lorem
ipsum</Label>
【问题讨论】:
如何在 WPF 中的标签文本中添加换行符,如下所示?
<Label>Lorem
ipsum</Label>
【问题讨论】:
<Label><TextBlock>Lorem<LineBreak/>ipsum</TextBlock></Label>
您需要使用 TextBlock,因为 TextBlock 接受 Inline 对象的集合作为子对象。因此,您为 TextBlock 元素提供了三个内联项:Run Text="Lorem"、LineBreak 和 Run Text="ipsum"。
您不能执行以下操作:
<Label>Lorem<LineBreak/>ipsum</Label>`
因为标签接受一个内容子元素。
另外,不确定您的用例到底是什么,但请注意我在您的 Label 元素中放置了一个 TextBlock。是重复的吗?不是真的,看你的需要。这是一篇关于这两个元素之间差异的好文章:Difference between Label and TextBlock
【讨论】:
<TextBlock> <Run>First</Run> <LineBreak/> <Run>Second</Run> </TextBlock>
Lorem&#x0a;Ipsum
在 WPF 中,您可以使用值 "&#10;" 或 "&#xA;"
例如:
<Label Content="Lorem ipsum" />
(“10”是换行符的ASCII码)
或
<Label Content="Lorem
ipsum" />
(“A”是十六进制换行符的ASCII码)
【讨论】:
在 ViewModel 或 Model 中执行此操作时,我发现使用 Environment.NewLine 具有最一致的结果,包括本地化。它也应该直接在视图中工作,但我还没有测试过。
例子:
在视图中
<Label Content="{Binding SomeStringObject.ParameterName}" />
在 ViewModel 中:
SomeStringObject.ParameterName = "First line" + Environment.NewLine + "Second line";
【讨论】:
如何将多行工具提示添加到控件(例如按钮)的示例。工具提示有宽度限制,因此如果句子太宽,它会自动换行。
<!-- Button would need some properties to make it clickable.-->
<Button>
<Button.ToolTip>
<TextBlock Text="Line 1
Line 2" MaxWidth="300" TextWrapping="Wrap"/>
</Button.ToolTip>
</Button>
在 VS2019 + .NET 4.6.1 + WPF 上测试。
【讨论】:
<Label xml:space="preserve">text content
another line</Label>
好像也可以
【讨论】: