Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

Drag and Drop Feature in WPF TreeView Control

4.63/5 (23 votes)
29 Jan 2010CPOL2 min read 176.6K   22.8K  
Implementation of Drag and Drop feature in WPF TreeView Control

Introduction

Windows Presentation Foundation (WPF) is a new technology introduced in .NET 3.0 with the name of Avalon that enables rich control, design, and development of the visual aspects of Windows programs. A WPF application can run on desktop and on web browser as well.

WPF provides much ease in drag and drop operations among controls. Much of the work related to Drag and Drop has already been done and you just need to use them.

Using the Code

To enable Drag and Drop feature in WPF TreeView control, follow the steps given below:

  1. Set TreeView control’s property AllowDrop="True".
  2. Declare three events in TreeView control, i.e. “MouseDown”, “MouseMove”, “DragOver” and “Drop” events.
  3. XML
     <treeview.itemcontainerstyle>
    
        <style targettype="{x:Type TreeViewItem}">        
    <EventSetter Event="TreeViewItem.DragOver"  Handler="treeView_DragOver"/>
    <EventSetter Event="TreeViewItem.Drop" Handler="treeView_Drop"/>
    <EventSetter Event="TreeViewItem.MouseMove" Handler="treeView_MouseMove"/> 
    <EventSetter Event="TreeViewItem.MouseDown" Handler="treeView_MouseDown"/>
        </style>              
                    
     </treeview.itemcontainerstyle> 
  4. Implement the following events in your code:
    • MouseDown Event:
      C#
      private void TreeView_MouseDown
           (object sender, MouseButtonEventArgs e)
      {
          if (e.ChangedButton == MouseButton.Left)
          {
              _lastMouseDown = e.GetPosition(tvParameters);
          }
      }

      This event occurs when any mouse button is down. In this event, we first check the button down, then save mouse position in a variable if left button is down.

    • MouseMove Event:
      C#
       private void treeView_MouseMove(object sender, MouseEventArgs e)
       {
             try
             {
                 if (e.LeftButton == MouseButtonState.Pressed)
                 {
                     Point currentPosition = e.GetPosition(tvParameters);
      
                     if ((Math.Abs(currentPosition.X - _lastMouseDown.X) > 10.0) ||
                         (Math.Abs(currentPosition.Y - _lastMouseDown.Y) > 10.0))
                     {
                         draggedItem = (TreeViewItem)tvParameters.SelectedItem;
                         if (draggedItem != null)
                         {
                             DragDropEffects finalDropEffect =
                 DragDrop.DoDragDrop(tvParameters,
                     tvParameters.SelectedValue,
                                 DragDropEffects.Move);
                             //Checking target is not null and item is
                             //dragging(moving)
                             if ((finalDropEffect == DragDropEffects.Move) &&
                     (_target != null))
                             {
                                 // A Move drop was accepted
                                 if (!draggedItem.Header.ToString().Equals
                     (_target.Header.ToString()))
                                 {
                                     CopyItem(draggedItem, _target);
                                     _target = null;
                                     draggedItem = null;
                                 }
                             }
                         }
                     }
                 }
             }
           catch (Exception)
           {
           }
      }
      

      This event occurs when mouse is moved. Here first we check whether left mouse button is pressed or not. Then check the distance mouse moved if it moves outside the selected treeview item, then check the drop effect if it's dragged (move) and then dropped over a TreeViewItem (i.e. target is not null) then copy the selected item in dropped item. In this event, you can put your desired condition for dropping treeviewItem.

    • DragOver Event:
      C#
      private void treeView_DragOver(object sender, DragEventArgs e)
       {
          try
          {                   
              Point currentPosition = e.GetPosition(tvParameters);
            
       if ((Math.Abs(currentPosition.X - _lastMouseDown.X) >  10.0) ||
      	(Math.Abs(currentPosition.Y - _lastMouseDown.Y) > 10.0))
              {
                  // Verify that this is a valid drop and then store the drop target
                  TreeViewItem item = GetNearestContainer
      			(e.OriginalSource as UIElement);
                  if (CheckDropTarget(draggedItem, item))
                  {
                      e.Effects = DragDropEffects.Move;
                  }
                  else
                  {
                      e.Effects = DragDropEffects.None;
                  }
              }
              e.Handled = true;
          }
          catch (Exception)
          {
          }
      }

      This event occurs when an object is dragged (moves) within the drop target's boundary. Here, we check whether the pointer is near a TreeViewItem or not; if near, then set Drop effect on it.

    • Drop Event:
      C#
      private void treeView_Drop(object sender, DragEventArgs e)
        {
            try
            {
                e.Effects = DragDropEffects.None;
                e.Handled = true;
      
                // Verify that this is a valid drop and then store the drop target
                TreeViewItem TargetItem = GetNearestContainer
                    (e.OriginalSource as UIElement);
                if (TargetItem != null && draggedItem != null )
                {
                    _target = TargetItem;
                    e.Effects = DragDropEffects.Move;
                }
            }
            catch (Exception)
            {
            }
       }
      

      This event occurs when an object is dropped on the drop target. Here we check whether the dropped item is dropped on a TreeViewItem or not. If yes, then set drop effect to none and the target item into a variable. And then MouseMove event completes the drag and drop operation.

Points of Interest

I read many articles and blogs on enabling drag and drop operation in WPF controls, and finally I am able to write this code. I hope it will help you to enable drag and drop operation in WPF TreeView control.

History

  • 29th January, 2010: Initial post

License

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