Built-in Drag and Drop
A
DiagramView can accept dragged shapes or nodes from
ShapeListBox and
NodeListView controls. To enable that, set its
AllowDrop property to
true. The view responds to
Shape objects dragged from
ShapeListBox 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 you must call the
ViewToDiagram method to convert the mouse position from view's to diagram's coordinate system (in
MeasureUnit and according to view's
ZoomFactor and
Scroll position). The following example demonstrates that:
C#
Copy Code
|
---|
void OnDiagramDragDrop(object sender, DragEventArgs e) { var position = e.GetPosition(diagramView); position = diagramView.ViewToDiagram(position);
var node = diagram.GetNodeAt(position); if (node == null) { node = diagram.Factory.CreateShapeNode( position.X - nodeSize.Width / 2, position.Y - nodeSize.Height / 2, nodeSize.Width, nodeSize.Height); }
node.Text = (string)e.Data.GetData(typeof(string));
e.Effects = DragDropEffects.Copy; e.Handled = true; }
Size nodeSize = new Size(96, 64); |
Initiate Drag Operation
You can start a drag-and-drop operation from the
Diagram by calling WPF'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
|
---|
protected override void OnPreviewMouseDown(MouseButtonEventArgs e) { if ((Keyboard.Modifiers & ModifierKeys.Shift) != 0) { var mousePosition = e.GetPosition(diagramView); mousePosition = diagramView.ViewToDiagram(mousePosition);
var node = diagram.GetNodeAt(mousePosition); if (node != null) { if (diagramView.Interaction != null) diagramView.Interaction.CancelNow(); DragDrop.DoDragDrop(this, node.Text, DragDropEffects.Copy); e.Handled = true; } } } |