Click here to Skip to main content
14,300,760 members

Drag and Drop Feature in WPF TreeView Control

Rate this:
4.63 (23 votes)
Please Sign up or sign in to vote.
4.63 (23 votes)
29 Jan 2010CPOL
Implementation of Drag and Drop feature in WPF TreeView Control


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.  <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"/>
  4. Implement the following events in your code:
    • MouseDown Event:
      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:
       private void treeView_MouseMove(object sender, MouseEventArgs e)
                 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 =
                             //Checking target is not null and item is
                             if ((finalDropEffect == DragDropEffects.Move) &&
                     (_target != null))
                                 // A Move drop was accepted
                                 if (!draggedItem.Header.ToString().Equals
                                     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:
      private void treeView_DragOver(object sender, DragEventArgs e)
              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;
                      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:
      private void treeView_Drop(object sender, DragEventArgs e)
                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.


  • 29th January, 2010: Initial post


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


About the Author

Irfan alam
Software Developer Technology Promotion International
Singapore Singapore
He is a Software Engineer working in Technology Promotion International.He has completed his BS(Software Engineering) from University of Karachi,Pakistan.he has scored 1st Position in the batch of 2008 in department of Computer Science and scored 2nd Position in faculty of Science.
He has been working in Technology Promotion International since June 2008. Here,he has worked on many Projects and learned many different technologies like WPF, Silverlight, LINQ and many more.His major expertise are in C#,ASP.NET,Crystal Report,SQL Server.

Comments and Discussions

QuestionNice sample Pin
Vardan Sargsyan4-May-17 8:28
memberVardan Sargsyan4-May-17 8:28 
QuestiondraggedItem = (TreeViewItem)tvParameters.SelectedItem is NULL Pin
Driftersdaddy23-Jan-15 6:21
memberDriftersdaddy23-Jan-15 6:21 
AnswerMagnificent solution, please accept my small improvements Pin
Olivier Jooris16-Jun-14 23:44
memberOlivier Jooris16-Jun-14 23:44 
Hi, great solution, I needed to ajust some small things and want to share them with you:

1. treeviewitem.header is a stackpanel: use the .ToText() extention method at the bottom (it gets you all text elements)
2. You do not need to copy the source to the target node: you can remove it and add it to the new one, please find the changed CopyItem code here under (--> this makes sure all event handlers in the items of the treeviewitem.header, like textbox_onchange, remain intact, if you copy this, they are lost)

Private Sub CopyItem(_sourceItem As TreeViewItem, _targetItem As TreeViewItem)

      'Asking user wether he want to drop the dragged TreeViewItem here or not
      If MessageBox.Show("Wil u " + DirectCast(_sourceItem.Header, StackPanel).ToText() + " onder groep " + DirectCast(_targetItem.Header, StackPanel).ToText() + " verplaatsen?", "", MessageBoxButton.YesNo) = MessageBoxResult.Yes Then
              'finding Parent TreeViewItem of dragged TreeViewItem
              Dim ParentItem As TreeViewItem = FindVisualParent(Of TreeViewItem)(_sourceItem)
              ' if parent is null then remove from TreeView else remove from Parent TreeViewItem
              If ParentItem Is Nothing Then
              End If

              If _targetItem Is Nothing Then
              End If

          Catch ex As Exception
              Throw New Exception("CopyItem failed: " & ex.Message)
          End Try
      End If
  End Sub

Extention of the stackpanel:
Public Module StackPanelExtentions
    ''' <summary>
    ''' override tostring: get all text elements in a stack panel
    ''' </summary>
    ''' <param name="input"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function ToText(ByVal input As StackPanel) As String
        Dim sb As New StringBuilder("")
        For Each it As UIElement In input.Children
            If it.GetType() Is GetType(TextBox) Then
                sb.Append(DirectCast(it, TextBox).Text)
                sb.Append(" ")
            ElseIf it.GetType() Is GetType(Label) Then
                sb.Append(DirectCast(it, Label).Content)
                sb.Append(" ")
            End If
        Return sb.ToString.Trim
    End Function
End Module

QuestionDrag and drop treeview items between two hierarchical treeviews, Pin
Jose Villanueva4-Apr-14 7:21
memberJose Villanueva4-Apr-14 7:21 
QuestionIf you drag one node to its child Pin
leiyangge20-Nov-13 15:14
memberleiyangge20-Nov-13 15:14 
BugAss Pin
ass45685219-Sep-13 2:53
memberass45685219-Sep-13 2:53 
GeneralMy vote of 5 Pin
Mohammed Hameed15-May-13 21:37
professionalMohammed Hameed15-May-13 21:37 
QuestionWith a stackpanel Pin
fifipil90910-Dec-12 0:28
memberfifipil90910-Dec-12 0:28 
QuestionWhere is the tvParameters? Pin
ptwistp125-Feb-12 7:38
memberptwistp125-Feb-12 7:38 
AnswerRe: Where is the tvParameters? Pin
Mike_ekim11-May-12 23:31
memberMike_ekim11-May-12 23:31 
GeneralGood basic sample to learn drag & drop Pin
jjtm27-May-11 5:49
memberjjtm27-May-11 5:49 
GeneralMy vote of 3 Pin
Daniel Brännström19-Jul-10 2:25
memberDaniel Brännström19-Jul-10 2:25 
GeneralMy vote of 1 PinPopular
Xcalllibur12-Jul-10 21:19
memberXcalllibur12-Jul-10 21:19 
GeneralProblem selecting the target after drop Pin
Member 41080191-Jul-10 1:18
memberMember 41080191-Jul-10 1:18 
GeneralConstructive critisism Pin
FantasticFiasco3-Feb-10 20:16
memberFantasticFiasco3-Feb-10 20:16 
GeneralAttached Behavior Pin
Steve Hansen29-Jan-10 1:54
memberSteve Hansen29-Jan-10 1:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 29 Jan 2010


47 bookmarked