Set TextBlock to preserve white space at the beginning and at the end?

一笑奈何 提交于 2019-12-03 11:09:02

问题


EDIT:

The code below actually works as I want - this question a little misleading. Please ignore it.


Normally when I set Text property of TextBlock like this:

TextBlock tb = new TextBlock();
tb.Text = "     Hello World ";

The whitespace at the beginning and at the end of text are not shown. The text shown by TextBlock is only Hello World. How can I set TextBlock to display them (i.e., not remove the whitespace)? Am I missing some property?


回答1:


In this case you don't need to use xml:space="preserve"

<TextBlock xml:space="preserve" Text="     Hello world!    " />

WILL display the whitespaces, however

<TextBlock>    Hello world!    </TextBlock>

won't.




回答2:


Re: "I just hope you are not using this to align your text. There are many other more elegant methods to do so."

Sounds like you might want to use the Padding property: http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.padding(VS.85).aspx.

See also the various alignment & margin properties.




回答3:


set the xml:space property to preserve in your XAML, i assume you are using WPF

<TextBlock xml:space="preserve" Text="     Hello world!    " />

EDIT: It is sometimes easier to do things in XAML. I just hope you are not using this to align your text. There are many other more elegant methods to do so.



来源:https://stackoverflow.com/questions/5934031/set-textblock-to-preserve-white-space-at-the-beginning-and-at-the-end

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