Pages

Saturday, August 11, 2012

Drag And Drop Item using ManipulationDelta in Windows 8 Metro Applications

I was thinking about how hard it can be to do drag and drop in a metro application. I started to Google for some information. I have done some drag and drop in a WPF application but never used it in a metro app.

The first thing that i was thinking about using was the Thumb control but that didn't work the way I wanted and needed for my application. In my application I needed to resize and rotate my items and the Thumb control didn't support that. So it was back to google to find something else to use. Then I found some information on MSDN that have everything I needed. It was the Quickstart: Touch input page at MSDN.

In the XAML code i just have a Canvas that i use as the Draggable surface and a rectangle that is the draggable item. The Rectangle have the manipulationmode property set to All to allow dragging, scaling and rotation (In this blog post i will only show how to do the dragging).
This is all the XAML I have added to the project.

XAML

            
        


In the codebehind we have a little more going on. In the Loaded event i'm  hooking up the ManipulationDelta event and I instantiate TranslateTransform to the DragableItem.RenderTransform. We use the translateTransform.X and translateTransform.Y to Reposition our Rectangle on the DrawCanvas.

C# Code-behind
public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            DragableItem.ManipulationDelta += DragableItem_ManipulationDelta;
            DragableItem.RenderTransform = new TranslateTransform();
        }

        private void DragableItem_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            Rectangle dragableItem = sender as Rectangle;
            TranslateTransform translateTransform = dragableItem.RenderTransform as TranslateTransform;

            translateTransform.X += e.Delta.Translation.X;
            translateTransform.Y += e.Delta.Translation.Y;
        }
    }


I hope this post will help someone. If you have any questions or if you want to correct me please post a comment.

You can find more information about this at the links below.
Quickstart: Touch input
TranslateTransform

No comments:

Post a Comment