如何在 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。是重复的吗?不是真的,看你的需要。这是一篇关于两个元素之间区别的好文章:Label and TextBlock之间的区别
在 WPF 中,您可以使用该值" "
或"
"
例如:
<Label Content="Lorem ipsum" />
(“10”是换行符的 ASCII 数字)
或者
<Label Content="Lorem
ipsum" />
(“A”是十六进制换行符的 ASCII 数字)
在 ViewModel 或 Model 中执行此操作时,我发现使用 Environment.NewLine 具有最一致的结果,包括本地化。它也应该直接在视图中工作,但我还没有测试过。
例子:
在视图中
<Label Content="{Binding SomeStringObject.ParameterName}" />
在视图模型中:
SomeStringObject.ParameterName = "First line" + Environment.NewLine + "Second line";
<Label xml:space="preserve">text content
another line</Label>
似乎也有效
如何将具有多行的 ToolTip 添加到控件(例如按钮)的示例。工具提示的宽度有限,因此如果句子太宽,它会自动换行。
<!-- 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 上测试。