Serialization in WPF Diagram (SfDiagram)

29 Nov 20249 minutes to read

Serialization is the process of converting the state of SfDiagram’s objects into a stream of bytes to recreate them when needed. Such streams can be stored in a database,as a file or memory. The reverse process is called deserialization.

Save

In SfDiagram, DataContractSerializer is used for serialization. The functionalities in DataContractSerializer are applicable to the SfDiagram serialization. It supports saving the SfDiagram into stream. The SfDiagram gets saved with all its properties.

//To Save as stream in file
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "Save XAML";
dialog.Filter = "XAML File (*.xaml)|*.xaml";
if (dialog.ShowDialog() == true)
{
    using (Stream str = File.Open(dialog.FileName, FileMode.CreateNew))
    {
        sfDiagram.Save(str);
    }
}

//To Save as memory stream
MemoryStream str = new MemoryStream();
sfDiagram.Save(str);

Load

On deserialization, the saved stream is used to load the SfDiagram’s nodes and connectors in current view. With this, you can continue working on the earlier saved SfDiagram by loading the appropriate stream.

//Load from saved XAML file
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
    using (Stream myStream = dialog.OpenFile())
    {
        sfDiagram.Load(myStream);
    }
}

//Load from saved memory stream
str.Position = 0;
sfDiagram.Load(str);

Has the diagram modified?

HasChanges property of diagram control is used to notify that the diagram has any unsaved changes. This property track all changes that are made through interaction and through the public APIs.

<!--Initialize the diagram-->
<Syncfusion:SfDiagram x:Name="diagram">
</Syncfusion:SfDiagram>
<!--Initialize the button to save the diagram-->
<Button x:Name="SaveButton" Content="Save" Click="SaveButton_Click">
</Button>
//Method to promote the save dialouge box when diagram has any unsaved changes.
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    if (diagram != null && diagram.HasChanges)
    {
        MessageBoxResult messageBoxResult = MessageBox.Show(
                            "Do you want to save the Diagram?",
                            "SfDiagram",
                            MessageBoxButton.YesNo);
        if (messageBoxResult == MessageBoxResult.Yes)
        {
            SaveDiagram();
        }
    }
}

//Method to save the diagram.
private void SaveDiagram()
{
    SaveFileDialog dialog = new SaveFileDialog();
    dialog.Title = "Save XAML";
    dialog.Filter = "XAML File (*.xaml)|*.xaml";
    if (dialog.ShowDialog() == true)
    {
        File.Delete(dialog.FileName);
        using (Stream s = File.Open(dialog.FileName, FileMode.OpenOrCreate))
        {
            diagram.Save(s);
        }
    }
}

How to serialize custom properties

In SfDiagram, you cannot serialize the Content and ContentTemplate of each and every diagramming objects. If you want to preserve the ContentTemplate of diagramming objects, keep them in resources and apply them once the diagramming objects are added to the Diagram page.

The custom properties in custom class derived from any of our SfDiagram’s interface or from any of the view model classes are serialized with the help of DataMember attribute.

public class NodeContent : INode
{
    [DataMember]
    public string NodeType
    {
        get;
        set;
    }
}

NOTE

SfDiagram’s interface and view model classes are created without DataContract attribute. So there is no need to add DataContract attribute for a class, which is derived from them.

How to serialize a custom class

You can serialize a business class with the help of DataContract attribute and SfDiagram’s KnownTypes property. You have to add DataContract attribute to serialize the whole class, which is not derived from a base class without DataContract attribute.

[DataContract]
public class NodeContent
{
    [DataMember]
    public string NodeType
    {
        get;
        set;
    }
}

Diagram.KnownTypes = () => new List<Type>()
{
    typeof(NodeContent)
};

View sample in GitHub

How to load SfDiagram’s old version in new version

You can load any of the old version SfDiagram’s stream in new version with the help of upgrade method. Refer to the following code example.

using (Stream myStream = dialog.OpenFile())
{
    sfDiagram.Upgrade(myStream);
    sfDiagram.Load(myStream);
}

Importing and Exporting Mind Map and Flowchart Diagrams using Mermaid Syntax

The SfDiagram supports saving diagrams in Mermaid syntax format. Mermaid is a Markdown-inspired syntax that automatically generates diagrams. With this functionality, you can easily create mind maps and flowcharts from Mermaid syntax data, simplifying the visualization of complex ideas and processes without manual drawing. Additionally, you can export your mind maps and flowcharts to Mermaid syntax, allowing for easy sharing, editing, and use across different platforms.

Save diagram as Mermaid syntax

The SaveDiagramAsMermaid method serializes the diagram into a Mermaid-compatible string format. This method is specifically designed for diagrams that utilize Flowchart and Mind map layouts. The following code illustrates how to save the diagram in Mermaid string format.

//Initialize the SfDiagram
SfDiagram Diagram = new SfDiagram();

// Initialize a layout for diagram
Diagram.LayoutManager = new LayoutManager()
{
    Layout = new FlowchartLayout()
    {
        Orientation = FlowchartOrientation.TopToBottom,
        YesBranchValues = new List<string> { "Yes", "True", "Y", "s" },
        YesBranchDirection = BranchDirection.LeftInFlow,
        NoBranchValues = new List<string> { "No", "N", "False", "no" },
        NoBranchDirection = BranchDirection.RightInFlow,
        HorizontalSpacing = 60,
        VerticalSpacing = 40,
    },
};

// Convert the diagram layout to a Mermaid string format.
string mermaidData = Diagram.SaveDiagramAsMermaid();

Load diagram from Mermaid syntax

You can load a diagram from the serialized Mermaid syntax data using the LoadDiagramFromMermaid method. The following code illustrates how to load a diagram from a Mermaid string data.

//Initialize the SfDiagram
SfDiagram Diagram = new SfDiagram();

// Initialize a layout for diagram
Diagram.LayoutManager = new LayoutManager()
{
    Layout = new FlowchartLayout()
    {
        Orientation = FlowchartOrientation.TopToBottom,
        YesBranchValues = new List<string> { "Yes", "True", "Y", "s" },
        YesBranchDirection = BranchDirection.LeftInFlow,
        NoBranchValues = new List<string> { "No", "N", "False", "no" },
        NoBranchDirection = BranchDirection.RightInFlow,
        HorizontalSpacing = 60,
        VerticalSpacing = 40,
    },
};

// Load the diagram using Mermaid text.
Diagram.LoadDiagramFromMermaid(mermaidData);

View Sample in GitHub

NOTE

Mermaid syntax data serialization and deserialization are only supported for Flowchart and Mind map layouts. Please ensure that your diagram uses one of these layouts to successfully load the data.

See Also

How to serialize the Content and ContentTemplate properties of a Node?