How to get drag working properly in silverlight when mouse is not pressed ?

Posted by Mrt on Stack Overflow See other posts from Stack Overflow or by Mrt
Published on 2010-04-14T07:55:11Z Indexed on 2010/04/14 10:23 UTC
Read the original article Hit count: 216

Filed under:
|

Hello,

I have the following code

  • xaml

    <Canvas x:Name="LayoutRoot" >
        <Rectangle Canvas.Left="40" Canvas.Top="40" Width="20" Height="20" Name="rec" Fill="Red" MouseLeftButtonDown="rec_MouseLeftButtonDown"   MouseMove="rec_MouseMove" />
    </Canvas>
    

  • code behind

public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); }

        public Point LastDragPosition { get; set; }
        private bool isDragging;

        private void rec_MouseMove(object sender, MouseEventArgs e)
        {
            if(!isDragging)
            {
                return;
            }

            var position = e.GetPosition(rec as UIElement);

            var newPosition = new Point(
                Canvas.GetLeft(rec) + position.X - LastDragPosition.X,
                Canvas.GetTop(rec) + position.Y - LastDragPosition.Y);

            Canvas.SetLeft(rec, newPosition.X);
            Canvas.SetTop(rec, newPosition.Y);

            LastDragPosition = e.GetPosition(rec as UIElement);
        }

        private void rec_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            LastDragPosition = e.GetPosition(sender as UIElement);
            rec.CaptureMouse();
        }
    }

This issue is the rectangle follows the mouse if the mouse left button is down, but I would like the rectangle to move even when the mouse left button isn't down. It works, but if you move the mouse very slowly. If you move the mouse to quickly the rectangle stops moving (is the mouse capture lost ?)

Cheers,

© Stack Overflow or respective owner

Related posts about drag-and-drop

Related posts about Silverlight