Skip Navigation LinksHome > View Post

Xaml. Embedding code

You can actually embed code into your Xaml as follows:

<x:Code><![CDATA[

public void ButtonClicked(object sender, RoutedEventArgs args)
{
MessageBox.Show("Yeah!");
}
    
]]></x:Code>

I initially thought this would be a useful trick for use with tools like XamlPad but, sadly, Xaml with embedded code needs compiling. Once compiled though, we could have used this code as an event handler for a button.

<Button Click="ButtonClicked">Click Me!</Button>

Note that we didn't need to declare a class to house our ButtonClicked method, the x:Code element could sit right next to the Button element.

Tags: Xaml

 
Josh Post By Josh Twist
2:57 AM
01 Mar 2007

» Next Post: Visual Studio 2005 Service Pack 1 Update for Windows Vista
« Previous Post: Xaml. Resource Dictionaries

Comments are closed for this post.

Posted by Andrew Hilton @ 28 Mar 2007 1:38 AM
But isn't that what XamlPad does every time it validates your code? (Forgive my ignorance)

Posted by Josh @ 28 Mar 2007 1:58 AM
Hi Andrew,

No, I don't believe it is. You can load Xaml at runtime and render it without compiling it. Which is how (I guess) XamlPad works and which is why you can't use it for certain scenarios.

I can post an example of how to do this if you think it will be interesting?

Posted by chaiguy1337 @ 10 Oct 2008 6:31 AM
This is good to know, but I really wish XAML let you embed delegates (i.e. anonymous methods) directly as the value for an event. That would be great for simple things that have just one or two lines of code and for which an entire method is overkill.

Probably the people who like to separate the code from the design wouldn't like that, but I'm not one of them. :P

© 2005 - 2014 Josh Twist - All Rights Reserved.