Wednesday 4 September 2013

Windows Phone - How to include ampersand (&) in the content of XAML elements like Combobox and TextBlock

/* XAML */
<ComboBox><ComboBoxItem> Awake & Alive</ComboBoxItem></ComboBox>
The above code throws exception :
Entity references or sequences beginning with an ampersand '&' must be terminated with a semicolon ';'.

The solution is to encode the special characters:
Use &amp; to encode the ampersand.
/* XAML */
<ComboBox><ComboBoxItem> Awake &amp; Alive</ComboBoxItem></ComboBox>
The same is applicable for other elements like TextBlock

Alternative:
/* XAML */
<ComboBox><ComboBoxItem><![CDATA[Awake & Alive]]></ComboBoxItem></ComboBox>
Explanation:
XAML being xml based, the xml parser when parsing an xml element, it also parses the text between XML tags, because XML elements can contain child elements.
CDATA indicated the text that should not be parsed by the XML parser. So any text that includes characters like '<' and '&' are to be included in CDATA, because these characters have special meaning in XML.
CDATA section starts with "<![CDATA[" and ends with "]]>"

No comments:

Post a Comment