Line breaks in XAML

Ever wondered how to add line breaks in XAML-designed windows, pages and user controls, e.g. a button’s caption? The \n special character is not converted to a line break but just printed out “as is”, and Visual Studio’s standard resource editor switches to the next row instead of adding a new line when pressing the Enter key… The following hints work, by the way, not only for mobile development but also for WPF desktop projects!

Line breaks in XAML attributes:

XAML attributes of type String may contain any special characters, as long as those are referenced as hex-codes. For example, a simple line break (\n) would be represented as 
, for \r\n you’d use 
 and so on.

<Button Content="This stretches over &#x0a;two lines." />

Line breaks in XAML elements:

To accomplish the same thing inside XAML tag elements (e.g., between <Button> . . . </Button>), the attribute xml:space must be set to "preserve". Then, line breaks and whitespace characters are directly inherited from the code file. However, this might bring about conflicts with code formatting, since even whitespaces used for code indenting will be preserved as blanks. To stay on the safe side, I’d recommend using hex-codes as described above:

<Button xml:space="preserve">This will produce
                             ugly blank spaces.</Button>
<Button xml:space="preserve">Better to use &#x0a;special characters.</Button>

Line breaks in resource files:

String values in resource files may include line breaks which will automatically be preserved – the problem is that Visual Studio does not allow pressing the Enter key for adding new lines (instead, the Enter key will switch focus to the next row). I usually write longer string values and those that contain special characters and line breaks in notepad or any other text editor, and then copy-paste it into Visual Studio’s resource editor. This way, all the special characters, white spaces and line breaks are preserved.