tags:

views:

4670

answers:

9

How can I add a line break to text when it is being set as an attribute i.e.:

<TextBlock Text="Stuff on line1 \n Stuff on line2" />

Breaking it out into the exploded format isn't an option for my particular situation. What I need is someway to emulate the following:

<TextBlock>
  <TextBlock.Text>
    Stuff on line1 <LineBreak/>
    Stuff on line2
  </TextBlock.Text>
<TextBlock/>
+24  A: 
<TextBlock Text="Stuff on line1&#x0a;Stuff on line 2"/>

You can use any hexidecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf, then you can use &#x0d;&#x0a;

By the way, note the syntax: It's the ampersand, a pound, the letter x, then the hex value of the character you want, and then finally a semi-colon.

ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.

Bob King
Spectacular, dude. That's exactly what I was trying to come up with.
MojoFilter
+3  A: 

Note that to do this you need to do it in the Text attribute you cannot use the content like

<TextBlock>Stuff on line1&#x0a;Stuff on line 2</TextBlock>
+1  A: 

Doesn't work in Buttons and Labels. =(

tpartee
it does - but you have to put a TextBlock as the content<Button><TextBlock Text="First LineSecond Line"/></Button>
Simon_Weaver
A: 

Also doesn't work with

<TextBlock><TextBlock.Text>NO USING ABOVE TECHNIQUE HERE</TextBlock.Text>

No big deal, just needed to use

<TextBlock Text="Cool &#x0a;Newline trick" />

instead.

Batgar
A: 

Many Thanks ! I really was forgetting the HTML Entities !:)

Seeker
A: 

thank you very much sir Bob King.

Nilesh
+2  A: 

You can add this...

 <TextBlock>
 <Run Text="First line"/> 
    <LineBreak/>
 <Run Text="Second line"/> 
    <LineBreak/>
 <Run Text="Third Line"/>
  </TextBlock>
Siva
I would like to Thank Simon_Weaver for Editing the answer.
Siva
A: 

May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML

<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>
scrat789