A simple way to create new XAML objects from string-based markup in Windows Store (Universal) applications
Posted: (EET/GMT+2)
Sometimes, you have the need to create user interface objects on the fly in your Windows 8 Store or Windows 8.1 Universal Apps.
The solution is simple: you can use the static Load method of the XamlReader class to pass in a piece of XAML code as a string, and get back a UIElement based on the string.
Basically, you can use the Visual Studio UI designer to easily create a template XAML code, and then use that string dynamically in your code. This is often easier than trying to construct the object directly as an object and set all the properties (which can become complex if you have multiple properties).
Here is an example that works in Windows store applications with the Universal Apps template. The example generates five checkbox components, and aligns them in a single vertical column:
using Windows.UI.Xaml.Markup;
...
// create an UI object based on the XAML template
string xamlTemplate = "<CheckBox Content=\"My CheckBox {0}\" HorizontalAlignment=\"Left\" " +
"Margin=\"75,{1},0,0\" VerticalAlignment=\"Top\" "+
"xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" />";
int yCoord = 100;
for (int i = 1; i < 6; i++)
{
string xaml = string.Format(xamlTemplate, i, yCoord);
UIElement uiObject = (UIElement)XamlReader.Load(xaml);
mainGrid.Children.Add(uiObject);
yCoord += 30;
}
Notice how the XAML template uses the placeholders {0} and {1} for the checkbox name and the y coordinate (top margin), respectively. The "mainGrid" variable would be any suitable parent component for the controls you create; in this case, it's a regular grid component.
Also, it is required that you specify the "xmlns" namespace as above. If you forget to add the namespace, the XamlReader.Load method will raise an exception of type XamlParseException with the message "No default namespace has been declared."
Hope this helps!