Skip to main content

Microsoft Silverlight

Answered Question Drag and Drop questionRSS Feed

(1)

StephenL
StephenL

Member

Member

14 points

12 Posts

Drag and Drop question

I am implementing drag and drop to allow the user to drag around a custom control and while it almost works, if the user moves to quickly, the mouse goes off my control and I stop getting mouse move events. My current work around is to end the drag on mouse leave but I would much rather not have the mouse run away. Does anybody have any ideas? My code is below.

Thanks

Stephen

private void mousePressed(object sender, EventArgs args)

{

    MouseEventArgs mea = args as MouseEventArgs;

    if (mea != null)

    {

        oldLoc = mea.GetPosition(
null);           isDragging = true;

    }

}

private void mouseReleased(object sender, EventArgs args)

{

    isDragging =
false;

}

// Hack since we dont get mouseMoved if user goes to quick and leaves us behind

// better would be to still get mouse events somehow

private void mouseLeft(object sender, EventArgs args)

{

    isDragging =
false;

}

private void mouseMoved(object sender, EventArgs args)

{

    if (! isDragging)

        return

    MouseEventArgs mea = args as MouseEventArgs;    if (mea != null)

    {

        Point newLoc = mea.GetPosition(null);

        double xOffset = newLoc.X - oldLoc.X;

        double yOffset = newLoc.Y - oldLoc.Y;

        mainCanvas.SetValue(Canvas.TopProperty, (double)mainCanvas.GetValue(Canvas.TopProperty) + yOffset);        mainCanvas.SetValue(Canvas.LeftProperty, (double)mainCanvas.GetValue(Canvas.LeftProperty) + xOffset);

        oldLoc = newLoc;

    }

}

Mark Rideout
Mark Rid...

Contributor

Contributor

2357 points

273 Posts

MicrosoftModerator
Answered Question

Re: Drag and Drop question

You need to capture the mouse in your MouseLeftButtonDown event handler:

sender.CaptureMouse();


And to be a good citizen you should call releaseMouseCapture. Check out this MSDN article on implementing Drag and drop: http://msdn2.microsoft.com/en-us/library/bb190645.aspx

-mark
Program Manager
Microsoft
This post is provided "as-is"

StephenL
StephenL

Member

Member

14 points

12 Posts

Re: Drag and Drop question

Thanks, Mark. I did see the javascript example before posting my question but when actually coding it in C# I mistakenly tried calling CaptureMouse on the framework element returned from InitializeFromXaml instead of on the sender. That just made things worse.

Stephen

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities