2

我有一个树视图。我在 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;
    }
4

3 回答 3

1

从您发布的代码来看,StartDrag 方法不应该在您的场景中被调用。但它显然是被调用的,因为你最终会进行 drop&drop 操作。在此处放置一个断点,您应该会看到为什么调用它。

附带说明,此代码

_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(sender as IInputElement); e.GetPosition(System.Windows.Application.Current.MainWindow) 的语句

于 2012-10-11T15:19:51.320 回答
1

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

于 2012-10-12T06:55:03.497 回答
0

尝试检查theContextMenu.IsVisible之前StartDrag

于 2019-09-06T11:09:53.513 回答