问题
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