This tutorial shows how to load graph data from XML and create diagram objects corresponding to the graph nodes and edges.
1. Right-click the project in Solution Explorer and choose Add -> New Item from the context menu. Create a new XML file called SampleGraph.xml and add to it content in the following form:
XML Copy Code |
---|
<?xml version="1.0" encoding="utf-8" ?> |
2. Set the file's "Build Action" property to "Content" and "Copy to Output Directory" to "Copy if newer".
3. Add a Loaded event handler to the WPF window:
Xaml Copy Code |
---|
<Window ... |
C# Copy Code |
---|
private void OnWindowLoaded(object sender, RoutedEventArgs e) |
4. Add the following variables to the Loaded handler. "nodeMap" maps diagram nodes to their identifiers, and "bounds" contains the default node size.
C# Copy Code |
---|
var nodeMap = new Dictionary<string, DiagramNode>(); |
5. Load the XML document and its root element using the Linq for XML API:
C# Copy Code |
---|
// load the graph xml |
6. Load the graph node elements and create their corresponding ShapeNode objects by calling the CreateShapeNode method of the Factory class. CreateShapeNode is just a shortcut to creating a ShapeNode instance using the "new" operator and adding it to the Nodes collection of the diagram. Additionally, this code maps the new node to the "id" attribute of the XML element, and sets the node's Text to the value of the "name" attribute.
C# Copy Code |
---|
// load node data |
7. Load the graph links and create corresponding DiagramLink objects. The Origin and Destination of the links are accessed by their ids through the "nodeMap" dictionary.
C# Copy Code |
---|
// load link data |
8. Arrange the diagram using the LayeredLayout class.
C# Copy Code |
---|
// arrange the graph |
9. Build and run the project. If everything is fine, you should see this representation of the graph: