Reading Silverlight Embedded XAML

April 15, 2008
No Comments.

Url: http://wilderminds.blob.core.windows.net/downloads/SeeMyXaml.zip
Silverlight Logo
I was talking with Walt Ritscher (of VB MVP fame) recently and he noted that he was trying to find a good way to grab XAML out of the assemblies in Silverlight 2. While Walt got a great answer from his brethren at Wintellect, I wanted to point out a quick way of reaching into the project to get the XAML.

One thing I noted was that I knew that the Silverlight 2 template reached into the assmebly to get the XAML at runtime so that code had to be there.  And it is there.  Its there in the ‘codegen’ class for every XAML based class (e.g. Page.xaml and other user controls). To get there easily, go to your Page.xaml and find the InitializeComponent call and press F12 to open that method.  This will open up the Page.g.xaml (the generated partial class). This leads us to this code:

public void InitializeComponent()
{
  if (_contentLoaded)
  {
    return;
  }
  _contentLoaded = true;
  System.Windows.Application.LoadComponent(this,
    new System.Uri("/SeeMyXaml;component/Page.xaml", 
                   System.UriKind.Relative));

  this.LayoutRoot = ((Grid)(this.FindName("LayoutRoot")));
  this.theXaml = ((TextBlock)(this.FindName("theXaml")));
}

Note the LoadComponent call.  It specifies a Uri to load the XAML right there is our project all along!

So what can we do with it?  I’ve crufted up a simple project (link provided above) that reads the XAML with a XDocument class then spits it out (with formatting but not coloring) in a TextBlock.  The code is dead simple:

// You may need to add System.Xml.Linq reference to get 
// the XDocument class
XDocument doc = XDocument.Load("/SeeMyXaml;component/Page.xaml");
theXaml.Text = doc.ToString(SaveOptions.None);

You should notice that we’re using that same path syntax to get the Page.xaml from the embedded resource. Simple, huh?