This is a simple example of generating xaml markup out of WPF controls, recreating the control from the xaml, and adding back into the visual tree.

The code included in this project starts with creating a button and setting a few properties.

It then uses XamlWriter.Save to convert the control into the XAML that represents the control and any properties that were set on it.

I show two examples of XamlReader.Parse to convert the XAML into a real control, firstly using an "in-code" string declaration, then using the string variable generated from the XamlWriter.Save, before.

I then add these controls to the Visual Tree by adding them to the StackPanel's Children property.

Finally, a MessageBox showing the resulting xaml of the StackPanel and it's Children, is exactly as you passed in and would expect.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
 
        Button originalButton = new Button();
        originalButton.Height = 50;
        originalButton.Width = 100;
        originalButton.Background = Brushes.AliceBlue;
        originalButton.Content = "Click Me";
 
        // Save the Button to a string.
        string savedButton = XamlWriter.Save(originalButton);
 
        FrameworkElement ele = (FrameworkElement)XamlReader.Parse("<Button Background=\"#FFF0F8FF\" Width=\"100\" Height=\"50\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">Click Me</Button>");
        FrameworkElement ele2 = (FrameworkElement)XamlReader.Parse(savedButton);
 
        LayoutRoot.Children.Add(ele);
        LayoutRoot.Children.Add(ele2);
 
        MessageBox.Show(XamlWriter.Save(LayoutRoot));
    }
}


This available in a demo project here.


This small article is part of a series of WPF "How To" articles, in response to real user questions on the MSDN WPF Forum.