Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slider does not drag in combination with IsMoveToPointEnabled behaviour

Tags:

c#

wpf

slider

I have IsMoveToPointEnabled on for my Slider, so when I click anywhere on the component the selector moves to my mouse. The problem is if I have this option on and click and hold the mouse down to drag the selector the selector doesn't move. Anyone know how to fix this?

like image 685
Kirk Ouimet Avatar asked May 26 '10 02:05

Kirk Ouimet


1 Answers

Inspired by Ray Burns Answer, the most simple way I found is this:

mySlider.PreviewMouseMove += (sender, args) =>
{
    if (args.LeftButton == MouseButtonState.Pressed)
    {
        mySlider.RaiseEvent(new MouseButtonEventArgs(args.MouseDevice, args.Timestamp, MouseButton.Left)
        {
            RoutedEvent = UIElement.PreviewMouseLeftButtonDownEvent,
                 Source = args.Source
        });
    }
};

With mySlider being the name of my Slider.

There are two issues with this solution (and most others in this topic):
1. If you click and hold the mouse outside of the slider and then move it on the slider, the drag will start.
2. If you are using the slider's autotooltip, it will not work while dragging with this method.

So here is an improved version, that tackles both problems:

mySlider.MouseMove += (sender, args) =>
{
    if (args.LeftButton == MouseButtonState.Pressed && this.clickedInSlider)
    {
        var thumb = (mySlider.Template.FindName("PART_Track", mySlider) as System.Windows.Controls.Primitives.Track).Thumb;
        thumb.RaiseEvent(new MouseButtonEventArgs(args.MouseDevice, args.Timestamp, MouseButton.Left)
        {
            RoutedEvent = UIElement.MouseLeftButtonDownEvent,
                 Source = args.Source
        });
    }
};

mySlider.AddHandler(UIElement.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler((sender, args) =>
{
    clickedInSlider = true;
}), true);

mySlider.AddHandler(UIElement.PreviewMouseLeftButtonUpEvent, new RoutedEventHandler((sender, args) =>
{
    clickedInSlider = false;
}), true);

clickedInSlider is a private helper variable defined somwhere in the class.

By using the clickedInSlider helper variable we avoid 1. The PreviewMouseButtonDown event is handled (because of MoveToPoint = true), so we have to use mySlider.AddHandler.
By raising the event on the Thumb instead of the Slider, we ensure that the autotooltip shows up.

like image 161
Tim Pohlmann Avatar answered Oct 12 '22 11:10

Tim Pohlmann