拖动;放下Treeview

时间:2009-06-22 09:02:37

标签: wpf drag-and-drop treeview

我正在尝试在我的树视图中拖放文件,但我不知道为什么在运行它并尝试拖动文件时它会崩溃。

以下代码就是我尝试过的。请帮忙。

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

1 个答案:

答案 0 :(得分:48)

这篇文章非常有帮助。 Drag drop wpf

此代码也可能对您有用。

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