Drag and Drop in Silverlight 3


One of the forums I found a question like how can I implement drag and drop in Silverlight. Today I got a chance to explore Silverlight drag and drop. I haven’t checked whether SL4 supports Drag and Drop, here is a simple implementation, which allow user to move the controls in runtime. I am using a rectangle as the control to drag and I placed the rectangle in a canvas.


<Canvas x:Name="LayoutRoot" Background="Gray">
    <Rectangle Height="20" Width="40" Fill="Blue" 
                MouseMove="Rectangle_MouseMove" Canvas.Left="109" Canvas.Top="88">

And here is the C# Code.

//To store the initial location of the control.
private Point _StartPoint = default(Point);
//To check whether user started dragging the control.
private bool _IsMouseCaptured = false;
private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    UIElement uiElement = sender as UIElement;
    //Reading the current position
    _StartPoint = e.GetPosition(uiElement);
    //Capturing the Mouse.
    this._IsMouseCaptured = uiElement.CaptureMouse();

private void Rectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    //Releasing the Mouse and setting the variable to false.
    UIElement uiElement = sender as UIElement;
    this._IsMouseCaptured = false;

private void Rectangle_MouseMove(object sender, MouseEventArgs e)
    //If the Mouse captured, set the Left and Top values of the control
    if (this._IsMouseCaptured)
        UIElement uiElement = sender as UIElement;
        Canvas.SetLeft(uiElement, (e.GetPosition(this).X - this._StartPoint.X));
        Canvas.SetTop(uiElement, (e.GetPosition(this).Y - this._StartPoint.Y));

Anuraj is currently working as Technical Lead. He is a regular speaker on Technology events. He has more than 11+ years experience with Microsoft.Net Technologies.

Facebook Twitter LinkedIn Google+