Adding Nodes to the Diagram

We have now implemented a DiagramSurface control. Now we need to add something to the diagram to be displayed.

In this step, we’ll add some elements to the diagram programmatically, just to get started. In a future step, we’ll provide a toolbox so the user can add their own elements to the diagram.

WPF Diagrams distinguishes between the DiagramSurface, the control on which a diagram is displayed, and the diagram model itself, which is represented by the DiagramSurface.Diagram property. When you add, remove or change diagram elements, you always work with the diagram model, not with the visual controls.

When you create a DiagramSurface, it has a default blank diagram. You can assign your own diagram, or modify the blank one. For the walkthrough, we’ll modify the blank diagram; you might assign your own diagram if you create a diagram from a business object, or load a diagram from a file or database.

To add nodes to the blank diagram, we just add ShapeNode objects to its Nodes to collection. We can do this in the window constructor, after the call to InitializeComponent. A ShapeNode needs to know two things: the kind of shape to display (which you can get from the DiagramShapes class), and the position and size of the shape, expressed as a boundary rectangle.

CopyAdding nodes to the diagram
ds.Diagram.Nodes.Add(new ShapeNode { Shape = DiagramShapes.Rectangle, Bounds = new Rect(20, 20, 80, 140) });
ds.Diagram.Nodes.Add(new ShapeNode { Shape = DiagramShapes.Ellipse, Bounds = new Rect(120, 120, 150, 70) });

At this point we can run up the application and see the two shapes, the rectangle and the ellipse. However, these shapes are displayed using WPF Diagrams’s default appearance, and we’d like to be able to override this to suit our application. We’ll see how to do this in the next step.

Next: Defining the Display Style.