Drag Element Behavior in windows 8 store apps. - nekgiann's blog - Site Root - StudentGuru

Drag Element Behavior in windows 8 store apps.

Here is a method I created that adds drag element behavior to any FrameworkElement. That method make use of TranslateTransform. You can easily play with any other RenderTransform option you like.

The method just takes the element you want to add the drag element behavior;

public static void AddDragElementBehavior(FrameworkElement el)
            UIElement parent=null;
            Point prevPoint;
            //the finger id, for multitouch support
            int pointerId=-1;

            //the function that runs when we are moving the mouse
            PointerEventHandler move = (delegate(object o, PointerRoutedEventArgs args)
                    //filter fingers, based on PointerId
                    if (args.Pointer.PointerId != pointerId)

                    var pos = args.GetCurrentPoint(parent).Position;
                    var tr=(TranslateTransform) el.RenderTransform;
                    tr.X += pos.X - prevPoint.X;
                    tr.Y += pos.Y - prevPoint.Y;
                    prevPoint = pos;

            //enabling move
            el.PointerPressed += delegate(object sender, PointerRoutedEventArgs args)

                    parent = (UIElement) el.Parent;
                    //making sure that parent captures pointer move
                    if (parent.GetValue(Panel.BackgroundProperty) == null)
                        parent.SetValue(Panel.BackgroundProperty, new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)));

                    //making sure that we have translate transform
                    if (!(el.RenderTransform is TranslateTransform))
                        el.RenderTransform = new TranslateTransform();

                    prevPoint = args.GetCurrentPoint(parent).Position;
                    parent.PointerMoved += move;
                    pointerId = (int) args.Pointer.PointerId;

            //disabling move
            el.PointerReleased += delegate(object sender, PointerRoutedEventArgs args)
                    if (args.Pointer.PointerId !=pointerId)
                    parent.PointerMoved -= move;
                    pointerId = -1;

And an example usage:
Enjoy! ;)