Silverlight

1. Create a Rectangle and set the RenderTransform to a TranslateTransform.

<Rectangle x:Name="rect" Width="50" Height="50" Fill="Blue" HorizontalAlignment="Left" VerticalAlignment="Top">
            <Rectangle.RenderTransform>
                <TranslateTransform x:Name="rectTranslateTransform" X="0" Y="0" />
            </Rectangle.RenderTransform>
    </Rectangle>


2. Register the MouseLeftButtonDown, MouseLeftButtonUp, and the MoseMove events for the rectangle.

  this.rect.MouseLeftButtonDown += new MouseButtonEventHandler(rect_MouseLeftButtonDown);
  this.rect.MouseLeftButtonUp += new MouseButtonEventHandler(rect_MouseLeftButtonUp);
  this.rect.MouseMove += new MouseEventHandler(rect_MouseMove);


3. In the MouseLeftButtonDown and MouseLeftButtonUp event you will capture and release the capture of the mouse, respectively.  Also, you will need to store if the mouse is captured.  


// Stores if the mouse is captured
private Boolean isRectMouseCapture = false;

void rect_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    this.rect.ReleaseMouseCapture();
    isRectMouseCapture = false;
}

void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    this.rect.CaptureMouse();
    isRectMouseCapture = true;
}
 
4. Finally, update the position if the mouse is captured and the mouse is moving.

void rect_MouseMove(object sender, MouseEventArgs e)
{
    if (isRectMouseCapture)
    {
        this.rectTranslateTransform.X = e.GetPosition(this).X;
        this.rectTranslateTransform.Y = e.GetPosition(this).Y;
    }
}
 

Results.


 

Maintain mouse position on object while dragging

The above example snaps the pointer to the top left of the object.  Face it, it’s annoying, what you really want is the mouse to maintain the position on the element while dragging. To solve this problem is simple.

1. Add a variable to save the position when the user clicks the object.

private Point clickPosition;

2. Save the position of where the mouse is located on the MouseLeftButtonDown event.  The updated MouseLeftButtonDown event looks like:

void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    clickPosition = e.GetPosition(sender as UIElement);
    this.rect.CaptureMouse();
    isRectMouseCapture = true;
}

3. Finally, in MouseMove event subtract the clickPosition from the mouse position.
    this.rectTranslateTransform.X = e.GetPosition(this).X - clickPosition.X;
    this.rectTranslateTransform.Y = e.GetPosition(this).Y - clickPosition.Y;
  

No comments: