Loading and Saving Diagrams

Most users will want to be able to save and re-load their diagrams. Because you have full access to the Diagram model, you can write your own code to load and save diagrams however you like. This allows you to persist using existing file formats, or as a relational model in a database. And if you are using the Diagram class as a view model over a business object, you would just store the business object and reconstruct the Diagram object on demand.

However, if you don’t have specific requirements for persistence, you can easily load and save diagrams as XML using the DiagramXmlSerializer.

Add a toolbar to your application as follows:

CopyXML
<ToolBar DockPanel.Dock="Top">
  <!-- Commands would be better here but we will use Click for simplicity -->
  <Button Name="OpenCmd" Click="OpenCmd_Click">Open</Button>
  <Button Name="SaveCmd" Click="SaveCmd_Click">Save</Button>
</ToolBar>

Here is the code for loading a diagram from a file:

CopyOpening a diagram from an XML file
private void OpenCmd_Click(object sender, RoutedEventArgs e)
{
  OpenFileDialog dlg = new OpenFileDialog();
  dlg.InitialDirectory = ProjectFolder;
  dlg.Multiselect = false;
  dlg.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";

  if (dlg.ShowDialog() ?? false)
  {
    DiagramXmlSerializer ser = new DiagramXmlSerializer();
    XDocument document = XDocument.Load(dlg.FileName);
    ds.Diagram = ser.Deserialize(document);
  }
}

Most of this code is just getting the filename and setting up a XmlReader over the file. The important lines are the last three:

CopyOpening a diagram from an XML file
DiagramXmlSerializer ser = new DiagramXmlSerializer();
XDocument document = XDocument.Load(dlg.FileName);
ds.Diagram = ser.Deserialize(document);

The code for saving a diagram to a file is similar, except it of course uses a SaveFileDialog and an XmlWriter, and calls the Serialize method instead of Deserialize:

CopyC#
DiagramXmlSerializer ser = new DiagramXmlSerializer();
XDocument document = ser.Serialize((Diagram)(ds.Diagram));
document.Save(dlg.FileName);

(In real world applications you would typically have a reference to the Diagram so you would not need the cast.)

We can now persist diagrams, but what if we need to exchange them with people who do not have access to our diagramming application? WPF Diagrams supports two ways of doing this: printing and exporting to bitmap.

Next: Printing the Diagram.