Silverlight Drag and Drop with RX

I highly recommend watching this video for the recently released RX extensions. It shows a walk through of implementing drag and drop in WPF. I took the same code and converted it to Silverlight for a fun exercise.

The major differences are the Mouse event names are different and you need to use a dispatcher to avoid cross thread issues. Check the Rx forums for more recent and efficient ways to do this for use in production code.

You will also need to add the System.CoreEx, System.Observable, and System.Reactive .Net references.


// Observe MouseMove Events 

var mouseMove = from evt in Observable.FromEvent<mouseeventargs>(this, "MouseMove")
select evt.EventArgs.GetPosition(this);

// Observe Mouse LeftButtonUp Event

var mouseUp = from evt in 
Observable.FromEvent<mousebuttoneventargs>(this, "MouseLeftButtonUp")
select evt.EventArgs.GetPosition(this);

// Observe MouseLeftButtonDown Event

var mouseDown = from evt in 
Observable.FromEvent<mousebuttoneventargs>(this, "MouseLeftButtonDown") 
select evt.EventArgs.GetPosition(this);

// Calculate Movement and Display

var q = from start in mouseDown
        from delta 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 delta;

q.Subscribe(value => textblock.Dispatcher.BeginInvoke(() =>
{
  Canvas.SetLeft(image,Canvas.GetLeft(image) + value.X);
  Canvas.SetTop(image,Canvas.GetTop(image) + value.Y);
}));

For a better explanation of this code check out John Skeets RX video at NDC 2010.

Leave a Reply

Your email address will not be published. Required fields are marked *