Rasto
Rasto

Reputation: 17744

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

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?

Upvotes: 27

Views: 21449

Answers (5)

Sherlock_Holmes
Sherlock_Holmes

Reputation: 109

Another solution is using the Run class like this:

<TextBlock>
    <Run Text="    "/>
    Hello world!
</TextBlock>

Upvotes: 1

C Naylor
C Naylor

Reputation: 31

You don't need to use the Text= property. This also works:

<TextBlock xml:space="preserve">Staff Contact Details        <Hyperlink>Click here</Hyperlink></TextBlock>

Upvotes: 3

Rob
Rob

Reputation: 91

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.

Upvotes: 9

Danield
Danield

Reputation: 125423

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.

Upvotes: 61

Tom Ceuppens
Tom Ceuppens

Reputation: 396

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.

Upvotes: 7

Related Questions