Skip Navigation LinksHome / Articles / View Article

Reading Silverlight Embedded XAML

+ Add to SilverlightShow Favorites
0 comments   /   aggregated from theADOguy on Apr 15, 2008  /  original article
(0 votes)
Categories: Learn , Tutorials , Tips and Tricks

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?

Add Comment | digg this

Share


Comments

Comments RSS RSS
No comments

Add Comment

 
 

   
  
  
   
Please add 1 and 5 and type the answer here:

Join the free SilverlightShow webcast 'Running Silverlight Outside the Browser and with Elevated Trust'. Sept 7th, 8 am - 9 am PDT.
In this live session Chris Anderson will cover configuring and debugging OOB mode, toast notifications, elevated trust, direct file access and much more.
Learn more | Register | See more webinars (hide this)