post icon

Silverlight Tip of the Day#27 – Displaying Special Characters in XAML

If you try to use the special/reserved characters in a string in XAML you will get a slew of errors in your Error List. Example reserved characters include:

  • <
  • >
  • &

For example, if you tried to do this:

<Button Width="100" Height="100" Content="Click &Me"/>

You would get these errors:

Error    5    Entity references or sequences beginning with an ampersand ‘&’ must be terminated with a semicolon ‘;’.   
Error    4    ‘"’ is an unexpected token. The expected token is ‘;’. Line 10, position 60.   

You can encode invalid characters for use in XAML by using the following encoding syntax:

Character

Encoding

<

&lt;

>

&gt;

&

&amp;

&quot;

space

&#160;

&apos;

(numeric character mappings)

&#[integer]; or

&#x[hex];

(nonbreaking space)

&#160; (assuming UTF-8 encoding)

So to fix the Button above you would insert “&amp;” wherever you want to use an “&”

<Button Width="100" Height="100" Content="Click &amp;Me"/>

Thank you,
–Mike Snow

3 Comments

Leave a comment
  1. Greg Lusk
    09. Jun, 2010 at 5:43 am #

    Does anyone know if there is a way to make XAML support the extended (higher character code) unicode math symbols? Specifically, I’d like to be able to display the angle symbol, which is &#8736 (dec), &#2220 (hex).

    XAML seems to support some of the higher codes, but not all. I may be wrong, but I think XML supports them all, so I would think that XAML would too.

  2. Martin
    01. Oct, 2010 at 2:24 am #

    Recently I created a tool that creates xml out of rich text and the xml is compatible to xaml. While working on that I came to heavy problems, when using open curly braces “{” in a string value that contains xaml which is assigned to the RichTextBox.Xaml property. A “value” exception is thrown and the assignment to the RichTextBox.Xaml property terminates.

    Do you know if this is mentioned as a bug and/or is there a possible solution or work around that avoids “value” exceptions in those cases?

    Sometimes (but not always) an exception is not thrown when a whitespace is added before the open curly bracket ” {“. But as far as I tested this out this workaround is not reliable.

  3. Akshaya
    21. Jun, 2011 at 1:24 am #

    Do you know, how can I do this for #?