WPF TextBlock 在多行上显示字符串 [英] WPF TextBlock Displaying String Over Multiple Lines
问题描述
我有一个字符串:
Item A\r\nItem B\r\nItem C
如何将此字符串绑定到 TextBlock 使其显示为:
How can I bind this string to a TextBlock so that it appears as:
Item A
Item B
Item C
谢谢
推荐答案
只要让 TextBlock
大到足以显示三行即可.如果 TextBlock
在 Text
中找到换行符和回车符,它能够包装文本.
Just make the TextBlock
big enough to show three lines. TextBlock
is capable of wrapping the text if it finds newline and carriage return in Text
.
另外,请确保换行符和回车符不是硬编码的.我的意思是这两者之间存在差异:
Also, make sure that the newline and carriage returns are not hard coded. What I mean is that there is a difference between these two:
MyString = @"Item A\r\nItem B\r\nItem C";
还有……
MyString = "Item A\r\nItem B\r\nItem C";
第二个字符串将在 TextBlock
中正确显示,但第一个将在一行中显示为Item A\r\nItem B\r\nItem C",因为换行符和回车字符是硬编码的,而不是转义字符.
The second string will display correctly in the TextBlock
but the first will just get displayed in a single line as "Item A\r\nItem B\r\nItem C" because the newline and carriage characters are hard coded instead of being escape characters.
您可以通过将硬编码的换行符和回车符替换为其转义序列来解决此问题:
You can fix that by replacing the hard coded newline and carriage characters with their escape sequences, by:
MyString = MyString.Replace("\\r\\n", "\r\n");
或最好通过:
MyString = MyString.Replace("\\r\\n", Environment.NewLine);
这篇关于WPF TextBlock 在多行上显示字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!