WPF Save Canvas to XAML and Load from XAML

Published on Monday, December 6, 2010

1: Save Canvas to XAML:

The canvas can include child controls:

                  FileStream fs = File.Open("xamlFileName.xaml", FileMode.Create);
                    XamlWriter.Save(contentCanvas, fs);

2: Load from XAML:

                    FileStream fs = File.Open(openFileDialog1.FileName, FileMode.Open, FileAccess.Read)
                    Canvas savedCanvas = XamlReader.Load(fs) as Canvas;

3: How to save canvas to a “completed” xmal file:

Above 1 only save Canvas information to XMAL file without a “completed” XML file format. So choose the following code example:

Page page = new Page();
StackPanel panel = new StackPanel();
page.Content = panel;
Button button = new Button();
button.Content = new Binding("Name");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("test.xaml", settings);
XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(writer);
XamlWriter.Save(page, manager);

The following is the result:

<?xml version="1.0" encoding="utf-8"?>
<Page xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button Content="{Binding Path=Name}" />