2015-06-13 238 views
1

我在WPF C#中爲Grid創建事件。事件「按下按鈕時」

The MouseMove事件。

我想觸發的MouseMove事件當鼠標左鍵按下保持事件甚至當鼠標離開電網甚至退出主窗口的。

當按鈕被按下保持鼠標移動事件網格整個屏幕直到按鈕Releasd

認爲這是鼠標移動事件法網格

private void Grid_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.LeftButton == MouseButtonState.Pressed) // Only When Left button is Pressed. 
     { 
      // Perform operations And Keep it Until mouse Button is Released. 
     } 
    } 

的目標是旋轉3D模型當用戶按住左鍵並當他移動鼠標,直到按鈕釋放旋轉模型。

這是爲了使用戶的程序和旋轉Eeasier。特別是執行長旋轉會導致鼠標離開網格。

我試圖使用while,但它失敗,你知道它是因爲單線程。

因此,我的想法是以某種方式在原始網格中按下按鈕時將屏幕全部展開,並將其保留至發佈。

當然虛擬網格女巫是隱藏的。

+0

感謝保持了關注!人們問問題20意見。我問問題6意見。 @AntonSizikov –

+1

http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title –

+0

感謝您的鏈接。我想我需要學習如何編寫好的標題:)但我試圖儘可能地解釋問題! @AntonSizikov –

回答

1

你想要做的是與事件流一起工作。據我理解你的流程應該如下:

  1. 鼠標左鍵按下
  2. 鼠標moved1(旋轉型)
  3. 鼠標moved2(旋轉型)

    ...

    N.左鼠標向上(停止旋轉)

有一個有趣的概念叫做Reactive Programminghttp://rxwiki.wikidot.com/101samples

沒有爲C#(Reactive-Extensions)庫

你的代碼可能看起來像這樣的:

// create event streams for mouse down/up/move using reflection 
var mouseDown = from evt in Observable.FromEvent<MouseButtonEventArgs>(image, "MouseDown") 
       select evt.EventArgs.GetPosition(this); 
var mouseUp = from evt in Observable.FromEvent<MouseButtonEventArgs>(image, "MouseUp") 
       select evt.EventArgs.GetPosition(this); 
var mouseMove = from evt in Observable.FromEvent<MouseEventArgs>(image, "MouseMove") 
       select evt.EventArgs.GetPosition(this); 

// between mouse down and mouse up events 
// keep taking pairs of mouse move events and return the change in X, Y positions 
// from one mouse move event to the next as a new stream 
var q = from start in mouseDown 
     from pos in mouseMove.StartWith(start).TakeUntil(mouseUp) 
        .Let(mm => mm.Zip(mm.Skip(1), (prev, cur) => 
          new { X = cur.X - prev.X, Y = cur.Y - prev.Y })) 
     select pos; 

// subscribe to the stream of position changes and modify the Canvas.Left and Canvas.Top 
// property of the image to achieve drag and drop effect! 
q.ObserveOnDispatcher().Subscribe(value => 
     { 
      //rotate your model here. The new mouse coordinates 
      //are stored in value object 
      RotateModel(value.X, value.Y); 
     }); 

實際構建的鼠標事件流是使用RX的一個非常經典的例子。

http://theburningmonk.com/2010/02/linq-over-events-playing-with-the-rx-framework/

您可以訂閱這個流在Windows構造事件的,所以你不依賴於電網,而且你沒有畫假網!

一些不錯的鏈接開始

  1. The Rx Framework by example
  2. Rx. Introduction
+0

哇。到我從未見過的許多新事物。我只知道'GetPosition' !!我應該開始學習你的代碼。謝謝。我希望在分析和理解你的代碼後,我可以得到好的結果。 –

+1

如果這個概念對你來說是新的,我建議看看這篇文章http://www.codeproject.com/Articles/52308/The-Rx-Framework-By-Example –

+0

謝謝你的不幸。 (有時候最小的優化比自己編寫程序更難!) –