Search
OLE Drag and Drop

Built-in Drag and Drop

DiagramView can accept dragged shapes or nodes from ShapeListBox, ShapeToolBar and NodeListView controls. To enable that, set its AllowDrop property to true. To allow dragging from ShapeToolBar, set toolbar's AllowDrag property. DiagramView responds to Shape objects dragged from ShapeListBox or ShapeToolBar by creating a ShapeNode at the drop position and setting its Shape property. Nodes dragged from NodeListView are cloned and the copies are added to the diagram.

Custom Drop Handling

DiagramView inherits standard drag-and-drop events from its base Control class. You could handle them to e.g. create nodes from dropped data, or to copy the data to existing node's fields. Note that DragEventArgs position is specified in screen coordinates, and the Diagram displayed by DiagramView has its own coordinate system, so you will need to convert the position in two steps. First call view's PointToClient method to get the drop position as view's local pixel offset, and then call ClientToDoc to get the diagram position (in MeasureUnit and according to view's ZoomFactor and Scroll position). The following example demonstrates that:

C#  Copy Code

void OnDiagramViewDragDrop(object sender, DragEventArgs e)
{
    var point = diagramView.ClientToDoc(
        diagramView.PointToClient(new Point(e.X, e.Y)));

    var node = diagram.GetNodeAt(point);
    if (node == null)
    {
        node = diagram.Factory.CreateShapeNode(
            point.X - nodeSize.Width / 2,
            point.Y - nodeSize.Height / 2,
            nodeSize.Width, nodeSize.Height);
    }

    node.Text = (string)e.Data.GetData(typeof(string));

    e.Effect = DragDropEffects.Copy;
}

SizeF nodeSize = new SizeF(40, 30);

Initiate Drag Operation

You can start a drag-and-drop operation from the DiagramView by calling .NET's standard DoDragDrop method. Depending on the context from which you start dragging, you might also need to cancel view's internal user interaction handling. The following example demonstrates how to drag node's text when Shift is pressed down.

C#  Copy Code

void OnDiagramViewMouseDown(object sender, MouseEventArgs e)
{
    if ((ModifierKeys & Keys.Shift) != 0)
    {
        var mousePosition = diagramView.ClientToDoc(e.Location);
        var node = diagram.GetNodeAt(mousePosition);
        if (node != null)
        {
            if (diagram.Interaction != null)
                diagram.Interaction.CancelNow();
            DoDragDrop(node.Text, DragDropEffects.Copy);
        }
    }
}