How to make WPF Slider Thumb follow cursor from any point

给你一囗甜甜゛ 提交于 2019-12-06 07:11:27

问题


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.


回答1:


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.



回答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;

     }
}


来源:https://stackoverflow.com/questions/15865734/how-to-make-wpf-slider-thumb-follow-cursor-from-any-point

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