wpf 在树视图中拖放

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1026179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:35:55  来源:igfitidea点击:

Drag & Drop in Treeview

wpfdrag-and-droptreeview

提问by don

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

回答by Erin

This article is very helpful. Drag drop wpf

这篇文章很有帮助。拖放 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;
}