I was having dinner with Walt Ritscher tonight when he posed an interesting question: how can a Silverlight app load its own XAML from an application assembly?
I thought I knew the answer, because I had just finished doing a lot of research into the various ways to package code and resources in Silverlight 2.0. And I knew that the XAML files in a Silverlight 2.0 app get embedded as resources in the application assembly, which in turn gets embedded in the application package (the application’s XAP file). But when I got back to my hotel and tried it, it didn’t work. So I played around some and found the secret incantation.
Here’s the Page.xaml file in the test app that I wrote:
<Grid x:Name=”LayoutRoot” Background=”White”>
<TextBlock x:Name=”Output” />
And here’s the output from the program:
Finally, here’s the code in Page.xaml.cs that produces the output by loading Page.xaml from the application assembly and assigning it to a TextBlock object:
StreamResourceInfo sri = Application.GetResourceStream
(new Uri(“SilverlightTestApp;component/Page.xaml”, UriKind.Relative));
StreamReader reader = new StreamReader(sri.Stream);
Output.Text = reader.ReadToEnd();
The trick is to include “assemblyname;component” in the URI passed to GetResourceStream, even though the assembly you’re loading from is the application assembly and not a library assembly. Normally you don’t have to include the assembly name if you’re targeting the application assembly, but this is obviously an exception–at least in Beta 1.
I don’t know how useful this information is, but it ought to make a good icebreaker at a Silverlight party.