Freigeben über


Simply Dragging in WPF, WP7 Silverlight and Silverlight 5

Gee, I just want to drag an ellipse in WPF or Silverlight 5 and all of the blogs/technical articles did a great job if you want to drag and drop things that were data, etc.  But what about just dragging a simple ellipse or image.

If I use Expression Blend it’s easy, use a behavior and bang that’s it.  But in the rarified world of software nerds, using Expression Blend is sometimes viewed as, well, not cool.  Which is dumb, but it does drive me to try new (or new to me).

So let’s take a look at how we would do the drag in a few lines of code, first place one ellipse in a canvas, use the tool kit and drag the ellipse over to a canvas (so I don’t have to write the XAML, or count it as “lines”).

Code Snippet

  1. <Ellipse x:Name="ellipse" Fill="#FFF4F4F5" Height="65"
  2.             Canvas.Left="83" Stroke="Black"
  3.             Canvas.Top="44" Width="144"
  4.             ManipulationDelta="ellipse_ManipulationDelta" />

The event ManipulationDelta was pointed out by Kenny Spade and you get to that by opening the properties, double click on the ManipulationDelta and let Visual Studio enter the event XAML for you

image

Now you can navigate to the event using the following:

image

Your code should look like the following:

 

Code Snippet

  1. private void ellipse_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
  2.         {
  3.             Canvas.SetLeft(ellipse, Canvas.GetLeft(ellipse) + e.DeltaManipulation.Translation.X);
  4.             Canvas.SetTop(ellipse, Canvas.GetTop(ellipse) + e.DeltaManipulation.Translation.Y);
  5.         }

And that’s it!  Run your code, and you should be able to move around your ellipse.

Next Ellipses in collision.