Load XAML File Dynamically

XAML is mostly used at design-time but there may be a time when you want to create XAML dynamically and/or load XAML in your code. The XamlWriter and the XamlReader classes are used to create and read XAML in code.

The XamlWriter and the XamlReader classes are defined in the System.Windows.Markup namespace and must be imported to use the classes as in the following:

using System.Windows.Markup;

The XamlWriter.Save method takes an object as an input and creates a string containing the valid XAML.

The code snippet in Listing 1 creates a Button control using code and saves it in a string using the XamlWriter.Save method.
 

// Create a Dynamic Button.

Button helloButton = new Button();

helloButton.Height = 50;

helloButton.Width = 100;

helloButton.Background = Brushes.AliceBlue;

helloButton.Content = "Click Me";

 

// Save the Button to a string.

string dynamicXAML = XamlWriter.Save(helloButton);

 

Listing 1

The XamlReader.Load method reads the XAML input in the specified Stream and returns an object that is the root of the corresponding object tree.

The code snippet in Listing 2 creates a XmlReader from a XAML and then creates a Button control using the XamlReader.Load method.
 

// Load the button

XmlReader xmlReader = XmlReader.Create(new StringReader(dynamicXAML));

Button readerLoadButton = (Button)XamlReader.Load(xmlReader);   

Listing 2

Up Next
    Ebook Download
    View all
    Learn
    View all