WPF 标签中的换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/483802/
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
Newline in a WPF-label?
提问by Natrium
How can I add a newline in the text of a label in WPF such as the following?
如何在 WPF 中的标签文本中添加换行符,如下所示?
<Label>Lorem
ipsum</Label>
回答by Szymon Rozga
<Label><TextBlock>Lorem<LineBreak/>ipsum</TextBlock></Label>
You need to use TextBlock because TextBlock accepts as children a collection of Inline objects. So you are giving the TextBlock element three Inline items: Run Text="Lorem", LineBreak, and Run Text="ipsum".
您需要使用 TextBlock,因为 TextBlock 接受 Inline 对象的集合作为子项。因此,您为 TextBlock 元素提供了三个内联项:Run Text="Lorem"、LineBreak 和 Run Text="ipsum"。
You can't do the following:
您不能执行以下操作:
<Label>Lorem<LineBreak/>ipsum</Label>`
because a label accepts one content child element.
因为标签接受一个内容子元素。
Also, not sure exactly what your use case is but notice I placed a TextBlock inside your Label element. Is it repetitive? Not really, depending on your need. Here's a good article on the differences between the two elements: Difference between Label and TextBlock
另外,不确定您的用例是什么,但请注意我在您的 Label 元素中放置了一个 TextBlock。是重复的吗?不一定,看你的需要。这里有一篇关于这两个元素之间差异的好文章:Difference between Label and TextBlock
回答by 00jt
in WPF you can use the value " "
or "
"
在 WPF 中,您可以使用该值" "
或"
"
For example:
例如:
<Label Content="Lorem ipsum" />
("10" is the ASCII number for newline)
(“10”是换行符的 ASCII 码)
or
或者
<Label Content="Lorem
ipsum" />
("A" is the ASCII number for newline in hex)
(“A”是十六进制换行符的 ASCII 码)
回答by HeyZiko
When doing this in the ViewModel or Model, I have found that using Environment.NewLine has the most consistent outcome, including localization. It should work directly in the View as well, but I haven't tested that.
在 ViewModel 或 Model 中执行此操作时,我发现使用 Environment.NewLine 具有最一致的结果,包括本地化。它也应该直接在视图中工作,但我还没有测试过。
Example:
例子:
In the View
在视图中
<Label Content="{Binding SomeStringObject.ParameterName}" />
In the ViewModel:
在视图模型中:
SomeStringObject.ParameterName = "First line" + Environment.NewLine + "Second line";
回答by Contango
An example of how to add a ToolTip with multiple lines to a control, such as a button. The tooltip is width limited so it will wrap if a sentence is too wide.
如何将多行工具提示添加到控件(如按钮)的示例。工具提示的宽度有限,因此如果句子太宽,它会换行。
<!-- 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>
Tested on VS2019 + .NET 4.6.1 + WPF.
在 VS2019 + .NET 4.6.1 + WPF 上测试。