2011-02-16 62 views
1

如果我使用两个事件处理程序PreviewMouseLeftButtonDown和PreviewMouseMove。我遇到的问题是,当触发PreviewMouseLEftButtonDown时,一切正常,但由于是拖放操作,因此左侧按钮保持不动。所以当他们拿着鼠标左键下来,PreviewMouseMove事件处理程序应该处理它,但它不会被调用后,才能在放开鼠标左键WPF拖放 - PreviewMouseMove + PreviewMouseLeftButtonDown不能一起工作?

这里是被称为第一

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

     } 
    } 

移动鼠标有没有办法解决?为什么在我释放鼠标左键之前,我不会阻止其他事件处理程序?

回答

2

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

0

它看起来像这个问题已经回答了一段时间,所以我不会详细说明太多,但为了其他人遇到同样的问题,您还可以使用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); 
    } 

,然后在目标中的“拖放”事件处理程序,你将有类似的信息(传递字符串属性的例子的缘故):

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

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