Draggable Window in Silverlight

Recently, i needed to implement a custom draggable stackpanel which houses a title stackpanel and a grid for inner controls. Although there are many easy-to-use draggable silverlight controls on internet, i prefered to add it manually by using MouseLeftButtonDown, MouseMove and MouseLeftButtonUp events. That is pretty easy as shown below


privatePoint beginP;

privatePoint currentP;

privatebool dragOn = false;

privatevoid spBrowser_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
e.Handled =true;
var c = sender as System.Windows.FrameworkElement;
this.dragOn = true;
this.beginP = e.GetPosition(null);
if (c != null)
{
c.Cursor =Cursors.Hand;
c.Opacity = 0.85;
c.CaptureMouse();
}
}

privatevoid spBrowser_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (this.dragOn)
{
var element = sender asFrameworkElement;
if (element != null)
{
element.Cursor =Cursors.Arrow;
element.Opacity = 1;
element.ReleaseMouseCapture();
}
this.dragOn = false;
}
}

privatevoid spBrowser_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (this.dragOn)
{
var element = sender asFrameworkElement;
this.currentP = e.GetPosition(null);
if (element != null)
{
var thickness = (Thickness)spBrowser.GetValue(MarginProperty);
double x0 = System.Convert.ToDouble(thickness.Left);
double y0 = System.Convert.ToDouble(thickness.Top);
double left = x0 + this.currentP.X - this.beginP.X;
double top = y0 + this.currentP.Y - this.beginP.Y;
element.Margin =newThickness(left, top, 0, 0);
}
this.beginP = this.currentP;
}
}

So, the stackpanel has drag-drop functionality but after i had added these events, i couldn’t manage to handle close-image MouseLeftButtonUp (inside the draggrable stackpanel). That was because the event is only handled by the container stackpanel. We can solve this issue by writing  “e.Handled=true” in the image’s MouseLeftButtonUp event. This way, the event is not routed to the parent stackpanel that I had handled above for dragging.

Have fun

Leave a comment