I came across a Stackoverflow question the other day: Add carriage return to string resource in WPF
In summary, what this person was trying to do is put new lines inside the text of an element in XAML and have the new lines be honored. In addition, this person was attempting to use XML character entities to embed the new line (“ ” in this case, which is a carriage return character).
1 | <span style="color:#0000ff"><</span><span style="color:#800000">system:String</span> <span style="color:#ff0000">x:Key</span><span style="color:#0000ff">="localizedMessage"</span><span style="color:#0000ff">></span>en-US&#13;Message<span style="color:#0000ff"></</span><span style="color:#800000">system:String</span><span style="color:#0000ff">></span> |
Okay, ignoring my pet peeve of using just a carriage return as a new line (because standard windows is carriage return plus line feed), unfortunately, all new line characters are being stripped from the supplied text.
(A quick note on XML character entities: on reading an XML document, an XML parser is required to convert the character entities to their actual character representation. This mean that whether there was an actual line break (pressing the enter key) or the character entities, those are ultimately the same thing. Character entities are simply a way to put in characters that tend to be difficult to represent in an XML document.)
That said, all we need to do is figure out why the new lines are being stripped from the text content of this element. A little Googling and MSDN spelunking tells us:
http://msdn.microsoft.com/en-us/library/cc189036(VS.95).aspx#whitespace
All whitespace characters (space, linefeed, tab) are converted into spaces.
There it is. Apparently Microsoft expected us to make mistakes and they are helping us out by normalizing what it considers to be superfluous characters into single spaces. This may sound silly until you realize HTML has been doing this for 15+ years and we’ve learned to live with it (and if they hadn’t kept that HTML behavior, they’d have lots of people familiar with HTML complaining about whitespace handling in XAML).
Luckily XAML (really, XML) has a very simple way to preserve whitespace in an element: use the xml:space attribute.
1 | <span style="color:#0000ff"><</span><span style="color:#800000">system:String</span> <span style="color:#ff0000">x:Key</span><span style="color:#0000ff">="localizedMessage"</span> <span style="color:#ff0000">xml:space</span><span style="color:#0000ff">="preserve"</span><span style="color:#0000ff">></span>en-US&#13;Message<span style="color:#0000ff"></</span><span style="color:#800000">system:String</span><span style="color:#0000ff">></span> |
With this one simple attribute, the XAML parser knows not to normalize whitespace for this element. Note that putting this attribute on a whole tree of elements because most elements don’t understand what to do with whitespace. Only put this on things that absolutely need it.