使用Reactive Extensions检测MouseDown和MouseMove事件

时间:2015-01-12 15:18:52

标签: c# wpf linq system.reactive

我有以下代码来监听从WPF ListView启动拖放事件。 这个想法是鼠标按下事件之后将是鼠标移动。一旦鼠标移动超过最小距离,拖拽下落动作将开始。

var mouseDowns = Observable.FromEventPattern<MouseEventArgs>(this, "PreviewMouseDown");
        var mouseMoves = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove").
            Where(
                x =>
                    x.EventArgs.LeftButton == MouseButtonState.Pressed ||
                    x.EventArgs.RightButton == MouseButtonState.Pressed);

        var drag = from mouseDown in mouseDowns
                   from mouseMove in mouseMoves
                   let initialPosition = mouseDown.EventArgs.GetPosition(null)
                   let currentPosition = mouseMove.EventArgs.GetPosition(null)
                   let mouseDifference = initialPosition - currentPosition
                   //where
                   //    (Math.Abs(mouseDifference.X) > MinimumDragDistance ||
                   //    Math.Abs(mouseDifference.Y) > MinimumDragDistance)
                   select mouseDifference;


        dragSubscription = drag.Subscribe(_ =>
         {
             Debug.WriteLine(string.Format("x: {0} y: {1}", _.X, _.Y));
             var dataObject = GetDataObject();
             DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Move);
         });

问题是在Linq中,每当一个PreviewMouseDown事件触发满足条件时,只捕获一个mouseMove事件,这意味着当我在列表中包含where语句时,mouseDifference总是0,哪个不符合条件。

是否有办法允许多个mouseMove事件发生,直到符合条件的事件发生?

1 个答案:

答案 0 :(得分:0)