2011-02-16 61 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); 
    } 

您仍然不捕獲鼠標事件,但在許多情況下它是一種快速簡單的方法來完成同樣的事情。