Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag & Drop in Treeview

I'm trying to drag and drop files in my treeview but I have no idea why it's breaking down if I run it and try dragging a file.

The code below is what I tried. Please help.

private void TreeViewItem_Drop( object sender, DragEventArgs e)
{
    TreeViewItem treeViewItem = e.Source as TreeViewItem;
    TreeViewItem obj = e.Data.GetData(typeof(TreeViewItem)) as TreeViewItem;

    if ((obj.Parent as TreeViewItem) != null)
    {
        (obj.Parent as TreeViewItem).Items.Remove(obj);
    }
    else
    {
        treeViewItem.Items.Remove(obj);
        treeViewItem.Items.Insert(0, obj);
        e.Handled = true;
    }
}

private void TreeViewItem_MouseLeftButtonDown( object sender,MouseButtonEventArgs e)
{
    DependencyObject dependencyObject = _treeview.InputHitTest(e.GetPosition(_treeview)) as DependencyObject;

    Debug.Write(e.Source.GetType().ToString());

    if (dependencyObject is TextBlock)
    {
        TreeViewItem treeviewItem = e.Source as TreeViewItem;

        DragDrop.DoDragDrop(_treeview, _treeview.SelectedValue, DragDropEffects.Move);
        e.Handled = true;
    }
}
like image 231
don Avatar asked Jun 22 '09 09:06

don


1 Answers

This article is very helpful. Drag drop wpf

This code may be of use to you as well.

Point _startPoint;
bool _IsDragging = false;

void TemplateTreeView_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed || 
        e.RightButton == MouseButtonState.Pressed && !_IsDragging)
    {
        Point position = e.GetPosition(null); 
        if (Math.Abs(position.X - _startPoint.X) > 
                SystemParameters.MinimumHorizontalDragDistance ||
            Math.Abs(position.Y - _startPoint.Y) > 
                SystemParameters.MinimumVerticalDragDistance)
        {
            StartDrag(e);
        }
    }           
}

void TemplateTreeView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    _startPoint = e.GetPosition(null);
}

private void StartDrag(MouseEventArgs e)
{
    _IsDragging = true;
    object temp = this.TemplateTreeView.SelectedItem;
    DataObject data = null;

    data = new DataObject("inadt", temp);

    if (data != null)
    {
        DragDropEffects dde = DragDropEffects.Move;
        if (e.RightButton == MouseButtonState.Pressed)
        {
            dde = DragDropEffects.All;
        }
        DragDropEffects de = DragDrop.DoDragDrop(this.TemplateTreeView, data, dde);
    }
    _IsDragging = false;
}
like image 112
Erin Avatar answered Oct 20 '22 21:10

Erin