(X) Hide this Watch the recording of the latest SilverlightShow webcast 'Running Silverlight Outside the Browser and with Elevated Trust'.
Join our next live webinar session by Braulio Diez - Sketchflow in Real Scenarios, on Sept 29th, 8am - 9am PDT.
Learn More | Sign Up | More Webinars by SilverlightShow


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
URL: http://adoguy.com/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)
  _contentLoaded = true;
    new System.Uri("/SeeMyXaml;component/Page.xaml", 
  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



Comments RSS RSS
No comments

Add Comment


Please add 7 and 6 and type the answer here: