Articles in this section
Category / Section

How to create parent and child relationship by drag and drop nodes in WPF Diagram (SfDiagram)?

2 mins read

The ItemDropEvent is triggered when the Node or Connector is dragged and dropped to another once the AllowDrop Constraints is enabled for Node or Connector in WPF Diagram (SfDiagram). Here, you get the source of the argument as drag item and Target as dropped items (List of items). This event helps us to reposition the nodes and relationship.

C#

 

public class DiagramVM : DiagramViewModel
{
  public DiagramVM()
  {
    Nodes = new ObservableCollection<CustomNode>();
 
    // Initialize Commands
    ItemAddedCommand = new Command(OnItemAdded);
    DropCommand = new Command(OnItemDrop);
  }
 
  // Method used to add the Allowdrop constraints to the dropped node
  // Allowdrop constraints is used to allow the itemdropped event to get the element as target element.
  private void OnItemAdded(object obj)
  {
    ItemAddedEventArgs args = obj as ItemAddedEventArgs;
    if (args.Item is CustomNode)
    {
      (args.Item as CustomNode).Constraints = (args.Item as CustomNode).Constraints.Add(NodeConstraints.AllowDrop);
    }
  }
 
  // Mehtod to create relation between drag and dropped nodes
  private void OnItemDrop(object obj)
  {
    ItemDropEventArgs args = obj as ItemDropEventArgs;
    if (!(args.Target is SfDiagram))
    {
      foreach (object targetElement in args.Target as IEnumerable<object>)
      {
         if (targetElement is CustomNode)
         {
           if ((args.Source as CustomNode).ParentId == null)
           {
             (args.Source as CustomNode).Id = "Node" + (Nodes as ObservableCollection<CustomNode>).Count.ToString();
             (args.Source as CustomNode).ID = (args.Source as CustomNode).Id;
             (args.Source as CustomNode).ParentId = (targetElement as CustomNode).Id;
 
             CreateConnector((args.Source as CustomNode).ParentId, (args.Source as CustomNode).Id);
             LayoutManager.Layout.UpdateLayout();
           }
         }
      }
    }
 
    else if (args.Target is SfDiagram)
    {
      if ((args.Source as CustomNode).ParentId == null)
      {
        (args.Source as CustomNode).Id = "Node" + (Nodes as ObservableCollection<CustomNode>).Count.ToString();
        (args.Source as CustomNode).ID = (args.Source as CustomNode).Id;
        (args.Source as CustomNode).ParentId = "";
        LayoutManager.Layout.UpdateLayout();
      }
    }
  }
}

 

 

ParentChildRelationship

 

The sample has provided to represent the parent-child relationship when drag and drop child node from the stencil to the parent node on the diagram. In the sample, you have restricted the drop of a child node in the diagram area.

 

View Sample in GitHub

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied