Reading XAML from a Silverlight Application Assembly

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:

<UserControl x_Class=”SilverlightTestApp.Page”

    

    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

    Width=”400″ Height=”300″>

    <Grid x_Name=”LayoutRoot” Background=”White”>

        <TextBlock x_Name=”Output” />

    </Grid>

</UserControl>

And here’s the output from the program:

XAML Output

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.

Stay Informed

Sign up for the latest blogs, events, and insights.

We deliver solutions that accelerate the value of Azure.
Ready to experience the full power of Microsoft Azure?

Atmosera is thrilled to announce that we have been named GitHub AI Partner of the Year.

X