Friday, December 30, 2011

WP7 Mouse LongPress/Hold with Reactive Extensions (Rx)

So, I'm digging through some old code and finding whatever little snippets that I believe others may find useful.  This one in particular allows you to handle a long-press event (pressing on the screen for longer than a specified time period), which I do not believe WP7 controls have by default; it's been a while since I've touched WP7 and haven't kept up with the SDK.

Anyway, the code uses Reactive Extensions to handle this gesture.  Lets pretend that we have a control, a stackpanel perhaps.  We can use the following code to handle the user pressing and holding onto our control for 1.1 seconds:

var stackpanel = new StackPanel();

var mousedownevent = Observable.FromEvent<MouseButtonEventArgs>(stackpanel, "MouseLeftButtonDown");
var mouseupevent = Observable.FromEvent<MouseButtonEventArgs>(stackpanel, "MouseLeftButtonUp");

var mouseholdevent = mousedownevent.Delay(TimeSpan.FromSeconds(1.1)).TakeUntil(mouseupevent).Repeat();

mouseholdevent.Subscribe(x => MessageBox.Show("LongPress with Rx!"));

I just thought this was something cool with reactive extensions so I decided to share it with everyone :)

No comments:

Post a Comment