How to: Resize a Canvas by Using a Thumb

This example shows how to use a Thumb control to resize a Canvas control.


The Thumb control provides drag functionality that can be used to move or resize controls by monitoring the DragStarted, DragDelta and DragCompleted events of the Thumb.

The user begins a drag operation by pressing the left mouse button when the mouse pointer is paused on the Thumb control. The drag operation continues as long as the left mouse button remains pressed. During the drag operation, the DragDelta can occur more than once. Each time it occurs, the DragDeltaEventArgs class provides the change in position that corresponds to the change in mouse position. When the user releases the left mouse button, the drag operation is finished. The drag operation only provides new coordinates; it does not automatically reposition the Thumb.

The following example shows a Thumb control that is the child element of a Canvas control. The event handler for its DragDelta event provides the logic to move the Thumb and resize the Canvas. The event handlers for the DragStarted and DragCompleted event change the color of the Thumb during a drag operation. The following example defines the Thumb.

<Thumb Name="myThumb" Canvas.Left="80" Canvas.Top="80" Background="Blue" 
      Width="20" Height="20" DragDelta="onDragDelta" 
      DragStarted="onDragStarted" DragCompleted="onDragCompleted"

The following example shows the DragDelta event handler that moves the Thumb and resizes the Canvas in response to a mouse movement.

void onDragDelta(object sender, DragDeltaEventArgs e)
    //Move the Thumb to the mouse position during the drag operation
    double yadjust = myCanvasStretch.Height + e.VerticalChange;
    double xadjust = myCanvasStretch.Width + e.HorizontalChange;
    if ((xadjust >= 0) && (yadjust >= 0))
        myCanvasStretch.Width = xadjust;
        myCanvasStretch.Height = yadjust;
        Canvas.SetLeft(myThumb, Canvas.GetLeft(myThumb) +
        Canvas.SetTop(myThumb, Canvas.GetTop(myThumb) +
        changes.Text = "Size: " +
                        myCanvasStretch.Width.ToString() +
                         ", " +

The following example shows the DragStarted event handler.

void onDragStarted(object sender, DragStartedEventArgs e)
    myThumb.Background = Brushes.Orange;
Private Sub onDragStarted(ByVal sender As Object, ByVal e As DragStartedEventArgs)
    myThumb.Background = Brushes.Orange
End Sub

The following example shows the DragCompleted event handler.

void onDragCompleted(object sender, DragCompletedEventArgs e)
    myThumb.Background = Brushes.Blue;
Private Sub onDragCompleted(ByVal sender As Object, _
                  ByVal e As DragCompletedEventArgs)
    myThumb.Background = Brushes.Blue
End Sub

For the complete sample, see Thumb Drag Functionality Sample.

See also