【问题标题】:WPF Drag and Drop - PreviewMouseMove + PreviewMouseLeftButtonDown cant work together?WPF拖放-预览MouseMove + PreviewMouseLeftButtonDown不能一起工作?
【发布时间】:2011-02-16 00:15:38
【问题描述】:

如果我使用两个事件处理程序,PreviewMouseLeftButtonDown 和 PreviewMouseMove。我遇到的问题是触发 PreviewMouseLEftButtonDown 时一切正常,但由于它是拖放操作,所以左键保持向下。因此,当他们按住左键时,PreviewMouseMove EventHandler 应该正在处理它,但直到他们释放鼠标左键后才会调用它

这是第一个被调用的内容

 private void FieldItemGrid_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e)
    {
        down = e.GetPosition(this);
        Grid fieldItemGrid = (Grid)sender;

        fieldItemGrid.Background = Brushes.White;
        _isDown = true;
        _startPoint = e.GetPosition(this);
        _originalElement = fieldItemGrid;
        this.CaptureMouse();
        e.Handled = true;


        _selectedElement = fieldItemGrid;
        DragStarted(e.GetPosition(this));
    }

这里一切正常,但问题是,如果他们在按住鼠标的同时移动鼠标,它不会执行 PreviewMouseMove 的以下处理程序

 private void FieldItemGrid_PreviewMouseMove(object sender, MouseEventArgs e)
    {

        if (_isDown)
        {
            if (_selectedElement != null)
            {
                DragDrop.DoDragDrop(_selectedElement, _selectedElement, DragDropEffects.Move);
            }
            if (_isDragging)
            {
                DragMoved(e.GetPosition(this));
            }

        }
    }

有没有办法解决这个问题?这样在我释放鼠标左键之前不会阻止我点击其他事件处理程序?

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    除非thisGrid,否则this.CaptureMouse() 将阻止包括Grid 在内的任何其他元素接收鼠标事件。对于拖放,您可能根本不需要捕获鼠标,但如果您确实捕获了鼠标,则需要使用 fieldItemGrid.CaptureMouse() 以便在捕获释放之前调用您的鼠标移动处理程序。

    【讨论】:

      【解决方案2】:

      这个问题好像回答了有一段时间了,就不过多阐述了,但是为了其他人遇到同样的问题,你也可以使用 DragDrop.DoDragDrop() 来实现拖拽单击鼠标按钮时,源代码隐藏中的方法。在目标上,您在 XAML 中将“AllowDrop”设置为 true 并处理“Drop”方法。您的实现会有所不同,但看起来像:

      private void MyUIElement_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
          {
              //find the clicked row
              var tempObject = e.Source as [whatever];
              if (tempObject == null) return;
      
              DragDrop.DoDragDrop(tempObject, tempObject.PropertyToBePassed, DragDropEffects.Copy);
          }
      

      然后在目标中的“Drop”事件处理程序中,您将拥有类似的东西(为了示例,传递一个字符串属性):

      private void MyTarget_Drop(object sender, DragEventArgs e)
          {
              string myNewItem = (string)e.Data.GetData(DataFormats.StringFormat);
              Debug.WriteLine("I just received: " + myNewItem);
          }
      

      您仍然不捕获鼠标事件,但在许多情况下,这是完成相同事情的一种快速简便的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-07
        • 2015-04-15
        • 2012-07-14
        • 1970-01-01
        • 2016-02-16
        • 2020-06-25
        • 2021-01-27
        相关资源
        最近更新 更多