WPF Save Canvas to XAML and Load from XAML

Published on Monday, December 6, 2010
wpf

1: Save Canvas to XAML:

The canvas can include child controls:

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

2: Load from XAML:

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

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");
panel.Children.Add(button);
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">
  <StackPanel>
    <Button Content="{Binding Path=Name}" />
  </StackPanel>
</Page>