Pages

Saturday, May 8, 2010

How to escape {} in XAML

Escape sequences are very important part for any programming language. XAML which is been widely used nowadays in form of Silverlight and WPF, has some literals that are of special meaning. While working with XAML, you often need those special characters to be treated as literals.

In case of XAML { --- } is treated as a markup extension. While parsing the XAML, the renderer finds { --- } and try to create an instance of an object just between the Curl braces. The object should be a markup extension. Thus if you want to use the braces like {Anything} as the content of a textbox, it will just strip the curl braces leaving only Anything.

This is where you need Markup extension.

<textblock text="this is {my} name">

This will produce the output as "this is my name" (with no braces around my. To solve this issue, WPF has escape sequence.

While WPF renders the output, it tries to find "{" (curl bracket) to declare the Markup extension. Now when the opening curl bracket is found, XAML checkes the very next character to see if this is an escape sequence or not. If the markup has "{}" (without anything inside curl braces), it will treat it as an escape sequence. Thus to escape the curl bracket you need to put "{}" just before putting the actual content. So the above textblock could be changed as :
<textblock text="{}this is {my} name">

and the output will be "this is {my} name".

No comments:

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.