3

I have such slider:

<Slider Minimum="0" Maximum="100" 
TickFrequency="1"
IsMoveToPointEnabled="True"
IsSnapToTickEnabled="False"/>

I want to make next behavior: when MouseDown occured at any point of slider, Thumb not only moves once to that point, but also following cursor until MouseUp occurs.

Sorry if it was asked already, i couldn't find that question.

aybe
  • 15,516
  • 9
  • 57
  • 105
Bohdan Sydor
  • 35
  • 1
  • 7

2 Answers2

4

This behavior will happen only when you drag the slider thumb itself, it is by design.

However, here's some code that will do it ;-)

Hook to the MouseMove event in XAML:

<Slider MouseMove="Slider_OnMouseMove" IsMoveToPointEnabled="True"/>

Then insert this code:

private void Slider_OnMouseMove(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        var slider = (Slider)sender;
        Point position = e.GetPosition(slider);
        double d = 1.0d / slider.ActualWidth * position.X;
        var p = slider.Maximum * d;
        slider.Value = p;
    }
}

Note :

  • You might have to take margins and padding of your slider into account should they differ, I haven't.
  • This was done on an horizontal slider.
  • Minimum value of my slider was 0, make sure to adjust the calculation should your minimum be negative.
  • Finally, it does seem to work only when IsMoveToPointEnabled is set.
Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
aybe
  • 15,516
  • 9
  • 57
  • 105
  • 1
    I've updated my code to use ActualWidth instead of Width as sometimes it is a NaN value what causes an exception. – aybe Apr 11 '13 at 16:21
2

Aybe's solution works better in the thumb_MouseMove event.

void timelineThumb_MouseMove(object sender, MouseEventArgs e)
{

     if (e.LeftButton == MouseButtonState.Pressed)
     {
         var thumb = sender as Thumb;

         Point pos = e.GetPosition(uiVideoPlayerTimelineSlider);
         double d = 1.0d / uiVideoPlayerTimelineSlider.ActualWidth * pos.X;
         uiVideoPlayerTimelineSlider.Value = uiVideoPlayerTimelineSlider.Maximum * d;

     }
}
Irene Kim
  • 21
  • 1