Initial Layout

I have problem doing the initial layout of the diagram.
I’m using custom layout which works great after the diagram is loaded.
The problem is to find the right moment to execute the layout during the initial display of the diagram.

At first I thought of using the LayoutCompleted event but the first time it fire the bounds of the daigram’s panel is -5,-5,10,10 and no node has ActualWidth or ActualHeight.

The fact that the bounds computation is done in the background make it hard to “catch” it.
I can schedule BeginInvoke with Background priority myself but it’s pretty weak in that on some cases the order might not be as I plan and tested.

It there any event, or combination of events that I can use to do an initial layout of the diagram the first time it is display?


Did you inherit your custom layout class from DiagramLayout or from one of the predefined layouts?

If it’s the former, try adding this code at the beginning of your DoLayout method:

foreach (Node n in nodes) { if (Double.IsNaN(n.Position.X)) n.Move(new Point(0, 0), false); }
That will make sure that if a node doesn’t already have a position it will be moved there. Some layouts depend on the previous node position, so this will help make sure it has a position and size.

If your layout is depending on the Diagram.Panel.ViewportBounds, you should add an event handler on the DiagramPanel.ViewportBoundsChanged to invalidate your layout.

I don’t think you should have to do any special invocation of your layout. Just leave it as the Diagram.Layout.

I actually do external layout using GraphSharp library. I create a “copy” of the nodes and links using GraphSharp data structures. The problem is that during the initial layout the nodes’ ActualWidth and ActualSize are not yet calculated, that is what causing the problem.