Early this morning I’m thinking about the draggable Image in Silverlight. I created a sample with simple snippets.
1. Create one Image, rectangle, and button.
2. Create an event handler for Image.
this.image1.MouseMove += new MouseEventHandler(image1_MouseMove);
this.image1.MouseLeftButtonDown += new MouseButtonEventHandler(image1_MouseLeftButtonDown);
this.image1.MouseLeftButtonUp += new MouseButtonEventHandler(image1_MouseLeftButtonUp);
3. Setting a variable
private bool isDragging = false; //dragging?
private Point mousePosition; //position of mouse
4. And now the events
private Point mousePosition; //position of mouse
4. And now the events
void image1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
this.image1.ReleaseMouseCapture();
isDragging = false;
} //Release the mouse
void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
mousePosition = e.GetPosition(sender as UIElement);
this.image1.CaptureMouse();
isDragging = true;
} //Pressed the left mouse button
void image1_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
this.imgTranslateTransform.X = e.GetPosition(this).X - mousePosition.X;
this.imgTranslateTransform.Y = e.GetPosition(this).Y - mousePosition.Y;
}
} //Dragging the Image
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
BitmapImage imgSrc = new BitmapImage();
imgSrc.SetSource(ofd.File.OpenRead());
image1.Source = imgSrc;
textBlock1.Text = "You can now drag the Image";
} // Open/Browsing the Image (binding Image)
{
this.image1.ReleaseMouseCapture();
isDragging = false;
} //Release the mouse
void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
mousePosition = e.GetPosition(sender as UIElement);
this.image1.CaptureMouse();
isDragging = true;
} //Pressed the left mouse button
void image1_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
this.imgTranslateTransform.X = e.GetPosition(this).X - mousePosition.X;
this.imgTranslateTransform.Y = e.GetPosition(this).Y - mousePosition.Y;
}
} //Dragging the Image
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
BitmapImage imgSrc = new BitmapImage();
imgSrc.SetSource(ofd.File.OpenRead());
image1.Source = imgSrc;
textBlock1.Text = "You can now drag the Image";
} // Open/Browsing the Image (binding Image)
