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).

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:

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.

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.