I've found situations where I want to store XAML in a database or call a PHP or ASP.NET page to generate & return XAML for me. It's really not that hard to take a XAML string and load it into our Silverlight application. In this post, I'll show you how to do so.
I'll be using the XamlReader.Load() method to load my XAML into my Silverlight application during runtime. There are some requirements to using the XamlReader.Load() method. The XAML string passed to the method must meet the following requirements:
The XAML content string must define a single root element.
The content string XAML must be well formed XML, as well as being parseable XAML.
The required root element must also specify a default XML namespace value. This is typically the Silverlight namespace, http://schemas.microsoft.com/client/2007.
In our example, I have a TextBox which accepts a XAML string. When I press the "Parse XAML" button, I will use the XamlReader.Load() method to load my XAML and then add the newly created Silverlight object to our Grid. Here is the XAML that I am going to attempt to parse. Take note that I've specified the default namespaces.
<TextBlock xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Text="TextBlock XAML has been load and added to our Grid!!" />
Once I paste my XAML string into the TextBox and click the "Parse XAML" button, the following code is executed:
Private Sub btnParse_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnParse.Click
I first clear any existing objects from the parsed XAML grid, then I load the XAML string and add the newly created object to our Grid.
XamlRuntime_Soln.zip (694.55 kb)