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.
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
BaseShape and 2 more classes -
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
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.
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.