WPF: Slider with an event that triggers after a user drags
Besides using the Thumb.DragCompleted
event you can also use both ValueChanged
and Thumb.DragStarted
, this way you don’t lose functionality when the user modifies the value by pressing the arrow keys or by clicking on the slider bar.
Xaml:
<Slider ValueChanged="Slider_ValueChanged"
Thumb.DragStarted="Slider_DragStarted"
Thumb.DragCompleted="Slider_DragCompleted"/>
Code behind:
private bool dragStarted = false;
private void Slider_DragCompleted(object sender, DragCompletedEventArgs e)
{
DoWork(((Slider)sender).Value);
this.dragStarted = false;
}
private void Slider_DragStarted(object sender, DragStartedEventArgs e)
{
this.dragStarted = true;
}
private void Slider_ValueChanged(
object sender,
RoutedPropertyChangedEventArgs<double> e)
{
if (!dragStarted)
DoWork(e.NewValue);
}
<Slider PreviewMouseUp="MySlider_DragCompleted" />
works for me.
The value you want is the value after a mousup event, either on clicks on the side or after a drag of the handle.
Since MouseUp doesn't tunnel down (it is handeled before it can), you have to use PreviewMouseUp.
You can use the thumb's 'DragCompleted' event for this. Unfortunately, this is only fired when dragging, so you'll need to handle other clicks and key presses separately. If you only want it to be draggable, you could disable these means of moving the slider by setting LargeChange to 0 and Focusable to false.
Example:
<Slider Thumb.DragCompleted="MySlider_DragCompleted" />