Dragging can be a useful feature in various scenarios especially in visually compelling ones. In Silverlight we can add drag capabilities to almost every element by using their MouseMove event. However, this method doesn't provide us a smooth drag experience. For example, when we drag a rectangle control by using its MouseMove event, dragging it to LHS immediately after RHS direction just stops the control. Therefore, we'll use Thumb control that is designed to be dragged with its specialized events. Let's begin:
1. Add a Grid control to your .xaml (or just use default LayoutRoot Grid)
2. Add two Grid Row Definitions to define rows
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="46"/>
</Grid.RowDefinitions>
3. Add a Thumb control and define its DragStarted, DragDelta (core dragging logic) and DragCompleted events as below:
<Thumb x:Name="myThumb" Height="50" HorizontalAlignment="Left" VerticalAlignment="Top" Width="50" DragDelta="myThumb_DragDelta" DragStarted="myThumb_DragStarted" DragCompleted="myThumb_DragCompleted" >
</Thumb>
4. Add a Textblock with with 4 Run control and 1 LineBreak to show which Thumb event is running and current coordinates of Thumb:
<TextBlock Grid.Row="1" TextWrapping="Wrap">
<Run Text="Events: "></Run>
<Run x:Name="EventRun" FontStyle="Italic"></Run>
<LineBreak></LineBreak>
<Run Text="Coordinates: "></Run>
<Run x:Name="CoordinatesRun" FontStyle="Italic"></Run>
</TextBlock>
5. In DragStarted and DragCompleted events just add the code below to populate TextBlock EventRun for informational purposes:
private void myThumb_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
{
EventRun.Text = "Drag Started";
}
private void myThumb_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
EventRun.Text = "Drag Completed";
}
6. DragDelta event is fired each time as soon as our Thumb Control is dragged. In this event's handler logic we first determine where Thumb control is (relative to Grid) just before it is moved on the screen. Then we calculate Thumb's new margin by adding current margin and how much it is dragged and assign this new margin to the Thumb's margin property (so it is moved).
private void myThumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
double marginLeft = myThumb.Margin.Left;
double marginTop = myThumb.Margin.Top;
double newMarginLeft = marginLeft + e.HorizontalChange;
double newMarginTop = marginTop + e.VerticalChange;
myThumb.Margin = new Thickness(newMarginLeft,newMarginTop,0,0);
EventRun.Text = "Drag Delta (Thumb is being dragged)";
CoordinatesRun.Text = newMarginLeft + "," + newMarginTop;
}
For informational purposes, populate EventRun and CoordinatesRun.
Hope, this helps.
