In this article we will see how can we implement Drag
and Drop in Silverlight 3 Application.Crating Silverlight
Fire up Visual Studio 2008 and create a Silverlight
Application. Name it as DragAndDropInSL3.
the solution in Blend 3 to design. Actually there is nothing to design but I
wanted a good Panel to Drag and Drop. J
I have just designed the Drag
you see in the Object and Timeline Pane I have added a Border and named it as
"MyPanel" and added a Grid with a Text Block saying "Information Bar".
the property side I have filled the Border with Linear Gradient and made the
Opacity to 50%.
Here is the Xaml code for your reference.
Dragging and Dropping is nothing but a
Translate Transform from one position to another. So we will add a Render
Transform for the Border.
As you see from above xaml code, I have
added the Translate Transform, gave it a name "BorderTransform" and values 0 to
X and Y.
Now come to C# code behind, open the file
Here is the idea how we will achieve drag and drop for
We will have a Boolean value isMouseCapture which will make us
true or false during dragging and dropping.
And, we will take a Point
variable clickPosition which will describe the position we clicked.
private Boolean isMouseCapture = false;
private Point clickPosition;
Now we will have three important events of the Border as
This is very
basic, when we drag an object we do Mouse Down, and move the object by Mouse
Move and dropping the object by Mouse Up. So we are taking the above events to
be fired respectively.
In Mouse Down event write the following code:
private void MyPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
clickPosition = e.GetPosition(sender as UIElement);
isMouseCapture = true;
In Mouse Move event write the
private void MyPanel_MouseMove(object sender, MouseEventArgs e)
this.BorderTransform.X = e.GetPosition(this).X - clickPosition.X;
this.BorderTransform.Y = e.GetPosition(this).Y - clickPosition.Y;
finally add the following code to Mouse Up event.
private void MyPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
isMouseCapture = false;
Now that we
are ready to test our application, press F5 to run the application and Drag and