WPF - 树视图 - 拖放和上下文菜单问题

时间:2012-10-11 14:36:48

标签: wpf drag-and-drop treeview

我有一个TreeView。我在TreeViewItems上设置了ContextMenu。当我通过右键单击某个项目并选择另一个项目(当ContextMenu打开时)打开ContextMenu时,我希望刚刚单击的项目无需任何操作即可被选中。 相反,框架认为我想拖动打开ContextMenu的项目,因此调用Drop处理程序。 我怎么解决这个问题。感谢

  private void TreeViewPreviewMouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed && !_isDragging)
        {
            var position = e.GetPosition(sender as IInputElement);
            if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
            {
                StartDrag();
            }
        }  
    }

    private void TreeViewPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        _startPoint = e.GetPosition(sender as IInputElement);
    }

    private void TemplateTreeViewDrop(object sender, DragEventArgs e)
    {
        if (_isDragging && (e.Source as TreeView) != null)
        {                
          dragQuestion = e.Data.GetData(typeof(QuestionListItem)) as QuestionListItem;
          dropQuestion = GetItemAtLocation(e.GetPosition(TemplateTreeView));
            if (dragQuestion != null && dropQuestion != null && dragQuestion!=dropQuestion)
            {
                viewModel.MoveQuestion(dragQuestion, dropQuestion);
            }
        }
        e.Handled = true;
        dragQuestion = null;
    }

    private void StartDrag()
    {
        var temp = TemplateTreeView.SelectedItem as QuestionListItem;
        if(temp == null) return;

        _isDragging = true;
        var data = new DataObject(temp);
        DragDrop.DoDragDrop(TemplateTreeView, data, DragDropEffects.Move);
        _isDragging = false;
    }

3 个答案:

答案 0 :(得分:1)

根据您发布的代码判断,在您的场景中永远不应该调用StartDrag方法。但很明显,因为你最终会进行掉落和放弃操作。在那里放一个断点,你应该明白为什么叫它。

旁注,此代码

_isDragging = true;
var data = new DataObject(temp);
DragDrop.DoDragDrop(TemplateTreeView, data, DragDropEffects.Move);
_isDragging = false;

不安全。你应该使用try / finally:

_isDragging = true;

try
{
    var data = new DataObject(temp);
    DragDrop.DoDragDrop(TemplateTreeView, data, DragDropEffects.Move);
}
finally
{
    _isDragging = false;
}

编辑:正如Dtex建议的那样,您也可以尝试替换您的e.GetPosition(发件人为IInputElement); e.GetPosition的声明(System.Windows.Application.Current.MainWindow)

答案 1 :(得分:0)

我发现了问题:在StartDrag方法中“var temp = TemplateTreeView.SelectedItem as QuestionListItem”我改变了var temp = GetItemAtLocation(e.GetPosition(TemplateTreeView));

答案 2 :(得分:0)

尝试在theContextMenu.IsVisible之前检查StartDrag