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:

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.

Jeff Prosise

View Comments

Recent Posts

8-Step AWS to Microsoft Azure Migration Strategy

Microsoft Azure and Amazon Web Services (AWS) are two of the most popular cloud platforms.…

5 days ago

How to Navigate Azure Governance

 Cloud management is difficult to do manually, especially if you work with multiple cloud…

2 weeks ago

Why Azure’s Scalability is Your Key to Business Growth & Efficiency

Azure’s scalable infrastructure is often cited as one of the primary reasons why it's the…

4 weeks ago

Unlocking the Power of AI in your Software Development Life Cycle (SDLC)

https://www.youtube.com/watch?v=wDzCN0d8SeA Watch our "Unlocking the Power of AI in your Software Development Life Cycle (SDLC)"…

1 month ago

The Role of FinOps in Accelerating Business Innovation

FinOps is a strategic approach to managing cloud costs. It combines financial management best practices…

1 month ago

Azure Kubernetes Security Best Practices

Using Kubernetes with Azure combines the power of Kubernetes container orchestration and the cloud capabilities…

2 months ago