November 14, 2011 at 4:13 AM
Occasionally it's useful to be able to load a piece of XAML as a string. This allows you to be able to decide, at runtime, what the UI will look like. This XAML can be composed beforehand and stored away in a file or the database, or it can be generated on-the-fly at runtime. In any case, the XAML can be a simple string and loaded into the the visual tree at runtime.
There are a few things you'll need to keep in mind, however.
Remove the Class attribute
The Class attribute is specified on the root element of a XAML document and specified the code file containing the code-behind code that is associated with the document. If this attribute is specified, it is expected that the class exists. Using code-behind kind of defeats the purpose of dynamically loading your XAML.
Explicitly Specify Namespaces and Assemblies
A good rule of thumb is that if you have to add a namespace to your document in order to be able to access its contents, you need to also specify the assembly containing the namespace. For example:
Load the XAML
Once you have clean XAML in a string format, you can load it as below:
var stringReader = new StringReader(value);
var xmlTextReader = new XmlTextReader(stringReader);
var control = XamlReader.Load(xmlTextReader);
In the above, "value" is a string that contains the XAML. We set it ass the source of a StringReader, which is set as the source of an XmlTextReader. This is passed into the XamlReader's Load method. Here, the XAML is parsed and a visual tree is constructed.
The Load method returns the root element of your control as a type "object". All that's left to do is to either set the control's DataContext or inject it into an already existing visual tree through, say, binding.