2009-06-22 22 views
15

Sto provando a trascinare e rilasciare i file nella mia vista ad albero, ma non ho idea del perché si stia corrompendo se lo eseguo e provo a trascinare un file.Drag & Drop in Treeview

Il codice seguente è quello che ho provato. Per favore aiuto.

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; 
    } 
} 

risposta

42

Questo articolo è molto utile. Drag drop wpf

Questo codice può essere utile anche a voi.

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; 
} 
+0

Grazie a Erin il codice ha aiutato a capire cosa è andato storto. Nel mio MousePreviewDown c'erano un paio di cose sbagliate, come il punto in cui non ho usato Math.Abs ​​(). Spiacente, il feedback è arrivato tardi :) – don

+2

Questo ha risolto il problema? (Se la domanda è contrassegnata come risposta ??) –

+0

ha risolto il problema per me – don