2015-06-13 162 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

谢谢你的不幸。 (有时候最小的优化比自己编写程序更难!) –