Reactive Drag in WPF

It has been way too long since I last updated my blog. Well I’ve been a bit lazy and busy at the same time, you guys get the excuse 😀

So without further ado, let’s get down to the fun stuff: doing a proper drag in WPF by using the Reactive Extensions.

I have covered some RX basics and usages 2 years ago for Silverlight/WP7. This is not only a revisit but more on using RX to solve a more complicated case as an example. Let’s start with the basics again:

var mouseDownEvents = Observable.FromEventPattern<MouseEventArgs>(this, "MouseLeftButtonDown");
var mouseMoveEvents = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove");
var mouseUpEvents = Observable.FromEventPattern<MouseEventArgs>(this, "MouseLeftButtonUp");

var dragEvents =
    from mouseDownPosition in mouseDownEvents
    from mouseMovePosition in mouseMoveEvents.StartWith(mouseDownPosition)
                                             .TakeUntil(mouseUpEvents)
    select mouseMovePosition;

dragEvents.Subscribe(eventPattern =>
{
    // Move things on UI.
});

This is a very simple drag example using RX, it is basically saying, react to all mouse move events, only after the mouse down event has happened and before any mouse up events have occurred. In the subscribe lambda expression, you can do things like get the current mouse position and use it to move things around on the UI.

However, in WPF a more appropriate way to do drag and drop, is to use the System.Windows.DragDrop.DoDragDrop method, so that you can define the drag source, drag data, allowed effects, etc…

dragEvents.Subscribe(eventPattern =>
{
    DragDrop.DoDragDrop(this, this, DragDropEffects.All);
});

It all looks nice and easy, except that:

  1. The DoDragDrop method is a synchronous method. Your code won’t pass that line until you drop.
  2. The method captures the mouse so no mouse up event will fire.

If no mouse up event is fired, the subscription won’t know when to stop, that means even after you dropped the object, the subscription will still react to mouse movements on the current element – a memory leak.

So it seems it’s reasonable enough to change the MouseLeftButtonUp event query to a Drop event query:

// This is the non-working query:
// var mouseUpEvents = Observable.FromEventPattern<MouseEventArgs>(this, "MouseLeftButtonUp");

// This should work:
var dropEvents = Observable.FromEventPattern<MouseEventArgs>(this,"Drop");

var dragEvents =
    from mouseDownEvent in mouseDownEvents
    from mouseMoveEvent in mouseMoveEvents.StartWith(mouseDownEvent)
                                          .TakeUntil(dropEvents)
    select mouseMoveEvent;

// ...

If you play around with this code for a while, you may realize that there are 2 major catches:

  1. If the current element is part of a complicated UI, you have no idea which element’s “Drop” event you should listen to. The drop could happen at anywhere.
  2. Even if you use VisualTreeHelper or Window.GetWindow to get the root element, if the drop happens on somewhere that does not allow dropping (e.g. the AllowDrop property is not set to true), then no Drop event will be raised.

So it looks like we can’t rely on drop either.

If you look at the code carefully, the drag detection is not a drag detection, it is really a “drag start” detection. As soon as you detect the starting of a drag, you can call DoDragDrop method and the framework can handle it from there. So we can see the problem as: how can I detect the drag start moment and not worry about the rest of the mouse movements?

Well logically the drag start is the one immediate mouse move event right after a mouse down event, so accordingly, we can modify the query to this:

var dragStartEvents =
    from mouseDownEvent in mouseDownEvents
    from mouseMoveEvent in mouseMoveEvents.StartWith(mouseDownEvent)
                                          .TakeUntil(mouseUpEvents)
                                          .Take(1)
    select mouseMoveEvent;

dragStartEvents.Subscribe(eventPattern =&amp;gt;
{
    DragDrop.DoDragDrop(this, this, DragDropEffects.All);
});

Now we are specifying query to only get 1 mouse move event after a mouse down event before any mouse up events. Now you can drag the hell out to anywhere without worrying about detecting where it is dropped.

In fact, the StartWith method includes the mouse down event before the first move event, so the subscription is not really reacting to the first move event, but rather, the mouse down event before that. I know this seems awkward, but I can reproduce this behaviour in .NET 4.0/4.5.

So if this annoys you, we can make the query a little bit error proof:

var dragStartEvents =
    from mouseDownEvent in mouseDownEvents
    from mouseMoveEvent in mouseMoveEvents.StartWith(mouseDownEvent)
                                          .TakeUntil(mouseUpEvents)
                                          .Skip(1)
                                          .Take(1)
    select mouseMoveEvent;

Now, this looks a solid query. It stops at mouse up events, skips the first mouse down event then take the real first mouse move event.

Preventing Accidental Drag

If you are a perfectionist, you may want to consider accidental drag detection. Basically we allow the mouse movement within a very small area around the mouse down position without triggering the drag. To do this, we need to alter the event queries a bit so that instead of getting event sequences, we get mouse position sequences:

var mouseDownEvents = Observable.FromEventPattern<MouseEventArgs>(this, "MouseLeftButtonDown").Select(pattern => pattern.EventArgs.GetPosition(this));
var mouseMoveEvents = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove").Select(pattern => pattern.EventArgs.GetPosition(this));
var mouseUpEvents = Observable.FromEventPattern<MouseEventArgs>(this, "MouseLeftButtonUp").Select(pattern => pattern.EventArgs.GetPosition(this));

Then we need to incorporate one more “Where” filter in the drag start detection query:

var dragEvents = 
    from mouseDownPosition in mouseDownEvents
    from mouseMovePosition in mouseMoveEvents
                                  .Where(mouseMoveEvent => 
                                             Math.Abs(mouseMovePosition.X - mouseDownPosition.X) > SystemParameters.MinimumHorizontalDragDistance
                                             || Math.Abs(mouseMovePosition.Y - mouseDownPosition.Y) > SystemParameters.MinimumVerticalDragDistance
                                        )
                                  .StartWith(mouseDownPosition)
                                  .TakeUntil(mouseUpEvents)
                                  .Skip(1)
                                  .Take(1)
    select mouseMovePosition;

There you go folks, take the reactive looking functional monad code (or whatever you want to call it) and rock hard out there!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s