WPF TextBlock Displaying String Over Multiple Lines

元气小坏坏 提交于 2019-12-10 16:16:37

问题


I have a string:

Item A\r\nItem B\r\nItem C

How can I bind this string to a TextBlock so that it appears as:

Item A
Item B
Item C

Thanks


回答1:


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.

EDIT: 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";

and...

MyString = "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");

or preferably by:

MyString = MyString.Replace("\\r\\n", Environment.NewLine);


来源:https://stackoverflow.com/questions/3797553/wpf-textblock-displaying-string-over-multiple-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!