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.
using System.Windows.Markup;
The XamlWriter.Save method takes an object as an input and creates a string containing the valid XAML.
// 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.
// Load the button
XmlReader xmlReader = XmlReader.Create(new StringReader(dynamicXAML));
Button readerLoadButton = (Button)XamlReader.Load(xmlReader);
Listing 2