views:

253

answers:

2

I am new to silverlight - I've seen the tutorials and all, what I am looking for are high-level steps required to implement drag&drop and maybe a bit of (pseudo)code just to get an idea.

Any help appreciated!

+3  A: 

Hi JohnIdol,
Could you explain exactly what you would like to achieve with drag and drop in Silverlight? The top answer in the question that you linked to links to this page: http://www.adefwebserver.com/DotNetNukeHELP/Misc/Silverlight/DragAndDropTest/

This contains a sample project with source that implements drag and drop (coincidentally, based on a sample I made for beta 1 of Silverlight 2 :-) ). What about this code is not suitable for your needs?

EDIT: The basic skeleton of a drag and drop implementation would look like:

bool isDragging = false;

void elementMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if (element.CaptureMouse())
    {
        isDragging = true;
        element.MouseMove += elementMouseMove;
        //start drag code goes here
    }
}

void elementMouseMove(object sender, MouseEventArgs e)
{
    //Drag code goes here
}

void element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (isDragging)
    {
        element.ReleaseMouseCapture();
        isDragging = false;
        element.MouseMove -= elementMouseMove;

        //Drop code goes here
    }
}

Add the MouseLeftButtonUp/Down handlers to the element that you want to drag.

In the MouseMove event handler, add the code that you want to execute during the drag: e.g. change Canvas.Top and Canvas.Left to match the mouse position. You can get the mouse position from the event args. You would probably want to get the position relative to the elements container.

In the MouseLeftButtonUp event handler, add the code that would execute when the "drop" occurs. For example, you might want to implement a "recycle bin" that elements can be dragged to. In that case, you would want to know what elements are underneath the mouse at the point of the drop. You can use VisualTreeHelper.FindElementsAtHostCoordinates, passing the mouse position relative to the application's root (use e.GetPosition(null)). Then if your "recycle bin" element is returned by FindElementsInHostCoordinates you know to execute the appropriate action.

Does this help answer you question?

KeithMahoney
JohnIdol
I edited the answer to include more information.
KeithMahoney
A: 

isn't MouseLeftButtonDown where you are supposed to be starting the capture, not on mouseleftbuttonup?

Paully