Click here to Skip to main content
Click here to Skip to main content

WPF Diagram Designer - Part 4

, 26 Mar 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
A Frankenbuild
WPF FlowChart Designer
  • Part 1 - Drag, resize and rotate items on a canvas
  • Part 2 - Toolbox, drag & drop, rubberband selection
  • Part 3 - Connecting items


In this article, I have added the following commands:

  • Open, Save
  • Cut, Copy, Paste, Delete
  • Print
  • Group, Ungroup
  • Align (Left, Right, Top, Bottom, Centered horizontal, Centered vertical)
  • Distribute (horizontal, vertical)
  • Order (Bring forward, Bring to top, Send backward, Send to back)

Note: I will only support Visual Studio 8.0 on .NET 3.5 !


The way I use WPF commands is straight forward, as described in the WPF SDK documentation, no extra infrastructure.


My first approach to group items was to use a DesignerItem object that should work as a group container. For this, I created a new instance of the DesignerItem class with a Canvas object as its content. On this canvas, I planned to position the designer items to be grouped. But before I could put the items on the group canvas, I had to remove them from the designer canvas because in WPF an element cannot be a child of two elements. If you try, you will get an InvalidOperationException with the following message:

"Specified element is already the logical child of another element. 
Disconnect it first."

So I removed the items from the designer canvas and put them on the group canvas. Now it is interesting to understand what WPF did behind the scenes: as soon as I removed an item from the designer canvas, its template was unloaded and when I added it to the group canvas, a new template was loaded. Now do you remember the last article where I showed you how to connect designer items? There I connected items via connectors, connectors that were part of the designer item's template, a template that is lost as soon as I remove the item from the designer canvas. You see the problem? I have connected designer items via their templates and so the designer item itself has absolutely no information about existing connections. All connection related information is isolated in the designer item's template.

Imagine a database diagram where the designer item's content is a database table. The table would never recognize any relation to other tables. One solution would be to tunnel the information from the template to the designer item to the table. A better solution is to redesign the application and divide the whole bulk into separate parts, e.g.

  • Template (view)
  • Designer item (view model)
  • Database table (model)

I will not start redesigning this code in the midst of an article, instead I will ride this 'view-only-approach' until the end of this article. The more painful this ride is, the more welcome a better solution will be. (I will cover a model backed designer in a future article.)

So let's continue. An alternative approach to group designer items uses the following interface:

 public interface IGroupable 
     Guid ID { get; } 
     Guid ParentID { get; set; } 
     bool IsGroup { get; set; } 

The idea is that the DesignerItem class has to implement this interface to become part of the grouping infrastructure, which works like this:

  • Create a new DesignerItem object with a unique ID and with its IsGroup property set to true
  • For each group member, set the ParentID to the ID of the group parent.

This is simple, but the real work happens when I modify items (Select, Move, Resize, Copy, ...); with each of these operations I have to consider an item's group status. Sounds like a lot of work, but it's not as painful as it would be without LINQ. For this, I have wrapped most of the work into the SelectionService class.

Note: The Connection class does not implement the IGroupable interface and so cannot directly be part of a group, but indirectly - since a connection is always attached to an item. This gives me the flexibility to re/connect items, no matter if they are members of a group or not.


To save a diagram, I have chosen to use a combination of XML and XAML. For the DesignerItem related data I use XML, and the content is serialized to XAML. Here again, please note that serializing a designer item's content to XAML only preserves the visual aspects and thus is used as a short term solution only. To create the XML file, I use LINQ. Since this is the first time I experiment with LINQ, don't expect it to be necessarily the "right" way to use it.

Here is an example of how I serialize designer items:

 XElement serializedItems = new XElement("DesignerItems",
                          from item in designerItems
                          let contentXaml = XamlWriter.Save(((DesignerItem)item).Content)
                          select new XElement("DesignerItem",
                                      new XElement("Left", Canvas.GetLeft(item)),
                                      new XElement("Top", Canvas.GetTop(item)),
                                      new XElement("Width", item.Width),
                                      new XElement("Height", item.Height),
                                      new XElement("ID", item.ID),
                                      new XElement("zIndex", Canvas.GetZIndex(item)),
                                      new XElement("IsGroup", item.IsGroup),
                                      new XElement("ParentID", item.ParentID),
                                      new XElement("Content", contentXaml)

The let keyword allows you to store the result of a sub-expression in a variable that can be used in a subsequent expression. Here I use this feature to save the serialized content in the contentXaml variable, which I use a few lines below. Finally, I use the Save method of the XElement class to store the element's underlying XML tree:



When loading a diagram from an XML file, we have to start with the designer items because we need their connectors to create connections. We have learned that connectors are part of the item's template, so the designer item has to load its template before we can continue. Fortunately the Control class provides the ApplyTemplate() method which forces the WPF layout system to load the control template so that its parts can be referenced.

In the previous article, I provided a mechanism to customize the ConnectorDecorator template, which allows you to freely position connectors around a designer item. That solution did apply the customized template after the designer item's Loaded event was fired and that event is not fired before the item becomes visible on your screen. Now the screen cannot be redrawn before the command has ended. So the only way is to set the customized ConnectorDecorator template explicitly within the Open command, see the SetConnectorDecoratorTemplate(item) method.

Note: When defining customized connectors, you must set the x:Name property. A connection uses the name to identify its source and sink connectors.

 <s:Connector x:Name="Left" Orientation="Left" 
    VerticalAlignment="Center" HorizontalAlignment="Left"/>

Copy, Paste, Delete, Cut

The Copy and Paste commands work analogous to the Open and Save commands, except that they are applied only to the selected items and that they read and write the serialized content to the Clipboard. The Delete command simply removes all selected items from the designer canvas' Children collection, and the Cut command finally is a combination of Copy and Delete command.

Align, Distribute

Not much to say about these commands, except that the reference item for alignment is the item that was selected at first (also called primary selection). This works only when you select items with the LeftMouseButton + Ctrl, or LeftMouseButton + Shift, but not if you use rubberband selection.


The Panel class (from which Canvas is derived) provides an attached property named ZIndex that defines the order on the z-plane in which the children appear, so we only have to change that property to bring an item forward or backward.


  • 25th March, 2008 -- Original version submitted


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author


Austria Austria
No Biography provided

Comments and Discussions

QuestionHelp me attach a property grid to the objects. Please PinmemberMember 1144469513-Feb-15 8:25 
QuestionSave as PDF PinmemberSaffa Shujah5-Dec-14 21:54 
QuestionChanging Color Components Pinmemberwgarzonalfonso22-Nov-14 3:29 
SuggestionSimpler way to cut, copy, paste, etc... [modified] PinmemberMember 1067105626-Aug-14 10:37 
GeneralThanks for your nice code . PinmemberRyan Cho25-Aug-14 21:44 
QuestionRotation PinmemberMember 971405614-Aug-14 14:38 
AnswerRe: Rotation PinmemberMember 971405621-Aug-14 9:35 
SuggestionRe: Rotation PinmemberMember 1067105626-Aug-14 11:00 
GeneralRe: Rotation PinmemberMember 971405627-Aug-14 7:14 
QuestionI'll extend the series on my website [modified] PinmemberLalaa2-Aug-14 11:33 
QuestionConector per Mausclick in einem Designerelement erstellen und an das Designerelement binden.?.?.? PinmemberMember 109164965-Jul-14 12:26 
GeneralMy vote of 1 PinmemberMember 1087019318-Jun-14 20:23 
GeneralRe: My vote of 1 PinmemberMember 4712601-Oct-14 22:27 
GeneralMy vote of 1 PinmemberMember 1087019318-Jun-14 20:23 
Questioncann't download the code of part4 Pinmemberhjgc200131-Mar-14 20:15 
QuestionDesignerItem MouseDown event does not fire PinmemberWang Chun Hsun26-Oct-13 0:21 
AnswerRe: DesignerItem MouseDown event does not fire PinmemberWang Chun Hsun30-Oct-13 4:02 
Question5 years later - Implemented your articles in an editor PinmemberDirkster9924-Sep-13 12:54 
QuestionHow to save and retrieve text Pinmembermadhu232724-Aug-13 23:42 
QuestionConnector in Toolbox Pinmemberaloktambi14-Aug-13 19:00 
AnswerRe: Connector in Toolbox Pinmemberaloktambi28-Aug-13 23:43 
QuestionHow to add text to this component Pinmembermadhu23278-Aug-13 23:09 
AnswerRe: How to add text to this component PinmemberMember 960453510-Aug-13 12:18 
GeneralRe: How to add text to this component Pinmembermadhu232724-Aug-13 23:45 
GeneralRe: How to add text to this component PinmemberSaffa Shujah6-Oct-14 7:22 
AnswerRe: How to add text to this component PinmemberMember 104371603-Mar-14 2:51 
QuestionLock designer PinmemberMateusz Slotwinski8-Aug-13 1:58 
AnswerRe: Lock designer PinmemberMateusz Slotwinski8-Aug-13 23:28 
GeneralMy vote of 5 PinmemberAuIr6-Aug-13 15:49 
QuestionGrouping question PinmemberWang Chun Hsun8-Jul-13 4:50 
AnswerRe: Grouping question PinmemberWang Chun Hsun8-Jul-13 5:19 
SuggestionRe: Grouping question PinmemberMember 1067105626-Aug-14 11:31 
GeneralMy vote of 5 PinmemberAmir Eshaq3-Jul-13 9:25 
QuestionVB.NET, .NET 3.0 Pinmemberfun-a-mir26-Jun-13 4:50 
QuestionModified version on GitHub Pinmemberjogibear998815-Jun-13 2:43 
QuestionHow to find id on entity set Pinmemberroeikalvo14-Apr-13 0:15 
QuestionFive stars!!! PinmemberKurt Richardson29-Mar-13 10:03 
QuestionZoom In/Out capability Pinmemberyuancn26-Mar-13 9:46 
AnswerRe: Zoom In/Out capability PinmemberDirkster9924-Sep-13 12:49 
QuestionHow to draw line on the designer Canvas PinmemberSujit Bhujbal7-Mar-13 21:09 
QuestionAbout table in ContentControl PinmemberDimkoc17-Feb-13 2:57 
GeneralMy vote of 5 PinmemberEric Ouellet28-Jan-13 11:15 
GeneralMy vote of 5 PinmemberKruglyj Max22-Nov-12 3:15 
QuestionPath Pinmemberjavorbg17-Nov-12 11:27 
Questionhow to define these shapestencils Pinmemberjie83041310-Nov-12 4:25 
QuestionGreat series of articles!! Have a small issue implementing logic EDIT - Fixed [modified] PinmemberWinstonSmith36-Nov-12 19:46 
QuestionImages drug and drop [modified] Pinmemberzzfima10-Oct-12 23:05 
Questiongeneralize an algorithm from an activity diagram PinmemberMember 943920120-Sep-12 20:15 
QuestionHow can I add wpfPropertyGrid in this project? Pinmemberaghapour.ahad6-Sep-12 2:44 
AnswerRe: How can I add wpfPropertyGrid in this project? PinmemberMember 1144469513-Feb-15 5:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150327.1 | Last Updated 26 Mar 2008
Article Copyright 2008 by sukram
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid