How to make WPF Slider Thumb follow the cursor from anywhere

I have such a slider:

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

I want to do the following behavior: when MouseDown happened at any point of the slider, Thumb not only moves once to this point, but also the cursor until MouseUp appears.

Sorry if he was already asked, I could not find this question.

+3
source share
2 answers

This behavior will only happen when you drag the large slider pointer, this is by design.

However, here is the code that will do this -)

Connect to the MouseMove event in XAML:

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

Then paste 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 may have to take the fields and fill in your slider into account, if they differ, I don’t know.
  • This was done on a horizontal slider.
  • The minimum value of my slider was 0, make sure you adjusted the calculation if your minimum is negative.
  • Finally, it only works if IsMoveToPointEnabled is installed.
+3
source

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; } } 
+1
source

Source: https://habr.com/ru/post/903006/


All Articles