Windows Phone 7 - Dynamically load XAML

Sometimes it is necessary to load an element like a shape dynamically from an file, resource or directly from a string into the corresponding API classes.

In Silverlight for Windows Phone 7 this can be done with the use of the XamlReader Class. This class can be found in the System.Windows.Markup namespace.

With the use of this class it’s very easy to create in memory representations of XAML object you created in tools like expression blend. In my example I created an ellipsis with a gradient fill and a gradient stroke.

<Ellipse Grid.Row="1" Height="40" VerticalAlignment="Top" HorizontalAlignment="Left" Width="40">
             <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF03063D" Offset="0"/>
                    <GradientStop Color="#FF333CD8" Offset="1"/>
                    <GradientStop Color="#FF06114D" Offset="1"/>
                    <GradientStop Color="#FF6F72FF"/>

If you try to load this xaml snippet with XamlReader.Load you will receive an error message. There are a view things you have to do with the snippet first.

  1. Remove the Grid.Row attribute.
  2. Add the required namespaces to the root (Ellipse) element
  3. Remove or ajust position information

After the modifications the XAML looks like this:

<Ellipse xmlns=\"\" xmlns:x=\"\" Height=\"40\" VerticalAlignment=\"Top\" HorizontalAlignment=\"Left\" Width=\"40\">
             <LinearGradientBrush EndPoint=\"0,1\" StartPoint=\"0.5,0\">
                    <GradientStop Color=\"#FF02076E\" Offset=\"0\"/>
                    <GradientStop Color=\"#FF272FBA\" Offset=\"1\"/></LinearGradientBrush>
             <RadialGradientBrush GradientOrigin=\"0.35,0.65\">
                    <GradientStop Color=\"#FF06114D\" Offset=\"1\"/>
                    <GradientStop Color=\"#FF6F72FF\"/></RadialGradientBrush>

Now the XAML is in the right shape and we can create the Ellipse objects with the following statement:

Ellipse ellipse = (Ellipse)XamlReader.Load("<Ellipse xmlns=\"\" xmlns:x=\"\" Height=\"40\" VerticalAlignment=\"Top\" HorizontalAlignment=\"Left\" Width=\"40\"><Ellipse.Stroke><LinearGradientBrush EndPoint=\"0,1\" StartPoint=\"0.5,0\"><GradientStop Color=\"#FF02076E\" Offset=\"0\"/><GradientStop Color=\"#FF272FBA\" Offset=\"1\"/></LinearGradientBrush></Ellipse.Stroke><Ellipse.Fill><RadialGradientBrush GradientOrigin=\"0.35,0.65\"><GradientStop Color=\"#FF06114D\" Offset=\"1\"/><GradientStop Color=\"#FF6F72FF\"/></RadialGradientBrush></Ellipse.Fill></Ellipse>");

In the example the XAML for the ellipse object is hard coded but in an real project you can store it in the project resources and load it from there.

string ellipseXAML;
System.IO.Stream st = this.GetType().Assembly.GetManifestResourceStream("Ellipse.xaml");
using(StreamReader reader = new StreamReader(st) )
        ellipseXAML = reader.ReadToEnd();