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
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;
}
}
来源:https://stackoverflow.com/questions/15865734/how-to-make-wpf-slider-thumb-follow-cursor-from-any-point