How to make WPF Slider Thumb follow cursor from any point

心已入冬 提交于 2019-12-04 15:05:22
Aybe

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.

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;

     }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!