oms
oms

Reputation: 441

How do I drag an element in Windows 8 XAML app?

XAML/C# Windows 8 app...

I have used MouseDragElementBehavior in XAML/C# to drag an element around on the screen.

Unfortunately the interactions assembly doesn't work while developing app for Windows 8.

How do I drag an element in Windows 8 XAML app?

Thanks.

EDIT: I found a sample example here: http://code.msdn.microsoft.com/windowsapps/Input-3dff271b/sourcecode?fileId=44758&pathId=962809525

Just copy the code and am able to drag my element. Having some issues will update, if need help.

Upvotes: 4

Views: 6938

Answers (2)

BryanJ
BryanJ

Reputation: 8563

Here is a overly simplified example based on ColinE's answer.

Consider a Canvas that has an ellipse:

<Canvas Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <Ellipse Fill="Red" 
             Canvas.Left="100"
             Canvas.Top="100"
             Width="100" 
             Height="100" 
             ManipulationMode="All" 
             ManipulationDelta="Ellipse_ManipulationDelta_1"/>
</Canvas>

Now in the code behind, you handle the ManipulationDelta:

private void Ellipse_ManipulationDelta_1(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        Ellipse myEllipse = (Ellipse)sender;
        Canvas.SetLeft(myEllipse, Canvas.GetLeft(myEllipse) + e.Delta.Translation.X);
        Canvas.SetTop(myEllipse, Canvas.GetTop(myEllipse) + e.Delta.Translation.Y);
    }

Upvotes: 1

ColinE
ColinE

Reputation: 70122

You need to handle the manipulation events on the element you wish to drag. And also, set ManipulationMode to a value other than None on the element.

  1. Handle ManipulationStarted to initialize your drag code
  2. Handle ManipulationDelta, inspecting the e.Delta values, and offset your element using a RenderTransform, or if in a Canvas, use the canvas coordinates.

Hope that helps.

Upvotes: 2

Related Questions