How to Create a Drag & Drop / Move, Zoom In & Out Content Control
Join the DZone community and get the full member experience.
Join For FreeHi.
As the Headline says, I will show you how to make a Drag and Drop / Move Content control. for this example I will use a canvas and an Image. But you can easily make it more generic by using a Content Control instead of the image.
<Canvas Grid.Row="1" Grid.Column="1" Grid.RowSpan="2" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" x:Name="ImageHolder" >
<Image Canvas.Left="0" MouseWheel="Img_MouseWheel" MouseMove="Img_MouseMove"
MouseDown="Img_MouseDown" MouseUp="Img_MouseUp" Panel.ZIndex="0"
Cursor="Hand" Canvas.Top="0" Height="150" Width="150" Source="sketch.jpg"
x:Name="Img">
</Image>
</Canvas>
As you can see we are using a canvas and an Image.
Implementing Drag and Move
to implement the drag and move we will need to use the following events:
- MouseDown
- MouseMove
- MouseUp
MouseDown event
private void Img_MouseDown(object sender, MouseButtonEventArgs e)
{
Img.CaptureMouse();
p = e.GetPosition(ImageHolder);
}
We register to this event to accomplish 2 actions
- capture the mouse - meaning if you move the mouse away from the image border it will still be considered as you are moving on the image border (you know what I am talking about, you drag to fast and then it stops moving).
- Establish a starting point on the screen by getting the position of the mouse relative to a control. It does not matter which control you choose as long as it does not move.
MouseMove event
private void Img_MouseMove(object sender, MouseEventArgs e)
{
Point x = e.GetPosition(ImageHolder);
if (e.LeftButton == MouseButtonState.Pressed)
{
Canvas.SetLeft(Img, Canvas.GetLeft(Img) + (x.X - p.X));
Canvas.SetTop(Img, Canvas.GetTop(Img) + (x.Y - p.Y));
}
p = x;
}
This is where the “Magic” happens :). All we need to do is calculate the difference between the mouse position we got at the MouseDown event and add it to the Canvas.Left and Canvas.Top property of the Image. We will then save the current position of the mouse for future MouseMove events.
MouseUp event
private void Img_MouseUp(object sender, MouseButtonEventArgs e)
{
Img.ReleaseMouseCapture();
}
Releasing the capture from the MouseDown event.
That’s it you can now drag that image around the canvas, Simple no? Wait till you see the Zoom In and Out.
Implementing Zoom In and Zoom Out
This is so easy it hurts.
All we need to use is the MouseWheel event:
private void Img_MouseWheel(object sender, MouseWheelEventArgs e)
{
Img.Height += e.Delta;
Img.Width += e.Delta;
}
Just add the delta to the Height and Width property of the Image and you are clear.
That’s it.
You can download a sample project from our Freebies Page. and don’t forget to grab our feed and stay updated.
Enjoy
Amit
Published at DZone with permission of Amit Raz. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments