With the release of Silverlight RC0 it was finally time to update this sample application. Let’s now go on with the tutorial and take a look at how the dragging capability of the Window is implemented, you can state if you want to enable or disable the dragging feature for an instance of the control simply by setting the ‘DraggingEnabled’ property.

All the code is encapsulated in the “Dragging functions” region, the Idea is quite simple, we will subscribe to the MouseLeftButtonDown, MouseMove and MouseLeftButtonUp events and handle the stuff from there:

  • MouseLeftButtonDown : here we capture the mouse, then we take note of the current Window position and the position where the user clicked (this value will be used to compute the offset of the movement). In the end we set the internal status variable that states we are inside a dragging operation.
void captionBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (DraggingEnabled) { // Bring the panel to the front Canvas.SetZIndex(this, currentZIndex++); // Capture the mouse ((FrameworkElement)sender).CaptureMouse(); // Store the start position this.initialDragPoint = e.GetPosition(this.Parent as UIElement); this.initialWindowLocation.X = Canvas.GetLeft(this); this.initialWindowLocation.Y = Canvas.GetTop(this); // Set dragging to true this.isDragging = true; } }
  • MouseMove: if we are in a dragging operation, we compute the offset and finally we set the new window position using the Canvas.SetLeft() or Canvas.SetTop() functions.
void captionBar_MouseMove(object sender, MouseEventArgs e) { if (this.isDragging) { Point position = e.GetPosition(this.Parent as UIElement); Canvas c = this.Parent as Canvas; // Move the panel double X = initialWindowLocation.X + position.X - initialDragPoint.X; if ((X >= 0) && (X + captionBar.ActualWidth <= c.ActualWidth)) Canvas.SetLeft(this, X); double Y = initialWindowLocation.Y + position.Y - initialDragPoint.Y; if ((Y >= 0) && (Y + captionBar.ActualHeight <= c.ActualHeight)) Canvas.SetTop(this, Y); } }

note that here we also set some limits for the position that the window can assume, actually we do not want to drag the window outside the Silverlight application area.

  • MouseLeftButtonUp: we release the mouse and we end the dragging operation.
void captionBar_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (DraggingEnabled) { // Release the mouse ((FrameworkElement)sender).ReleaseMouseCapture(); // Set dragging to false isDragging = false; } }


See you next time.

Example Solution:


Related Content