Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

The Simplest WPF Diagram Designer

0.00/5 (No votes)
5 Oct 2014 1  
If you want to implement the simplest drag-n-drop diagram designer.

Introduction

In this tip, I want to share how I've implemented the simplest diagram designer using WPF and C#. In later tips, I am going to expand this project to a fully functional mind mapper application.

For the next tip, see Part 2.

Code Structure

For now, the attached solution consists of only 1 project - MyDesigner. It has once again only 1 simple window (to fulfill the title).

It is possible to draw using only Shape class of the WPF, but if we want better interaction between shapes, we have to introduce some wrappers - with an additional logic.

In this case, we have a base abstract class BaseShape and 2 more classes - MyShape and MyConnector who inherit from it. There is also one another shape class - MyLine, it is separate as it is 1 dimensional shape. Each line has 2 connectors which can be glued either to shape or to canvas itself.

Model class is simple for now as well. It has 3 collections - for shapes, lines and connectors - and a property for an active tool - it can be either hand to drag shapes over canvas or a line to draw new lines.

Points of Interest

Panel.SetZIndex(shape, 10);

As shapes are added one after another and it is possible to overlap them, we have to organize shapes by layers. There are 3 layers. Z index = 0 for general shapes, Z index = 10 for lines and Z index = 11 for connectors. That way, Connectors are on the top and lines are above shapes.

Mouse.Capture(MyCanvas);

This means that all mouse events will relate to the canvas, even if the mouse should be moved outside it. Without it, moving would be stopped as soon as mouse moved outside the canvas.

var newX = currentPoint.X - shape.Width / 2;
var newY = currentPoint.Y - shape.Height / 2;

if (newX < 0) newX = 0;
if (newX + shape.Width > MyCanvas.ActualWidth) newX = MyCanvas.ActualWidth - shape.Width;

if (newY < 0) newY = 0;
if (newY + shape.Height > MyCanvas.ActualHeight) newY = MyCanvas.ActualHeight - shape.Height;

We don't want to move shapes outside the canvas so we have to restrict new coordinates.

Enum binding to the radio buttons is as described here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here