如何使 WPF Slider Thumb 从任意点跟随光标

How to make WPF Slider Thumb follow cursor from any point(如何使 WPF Slider Thumb 从任意点跟随光标)
本文介绍了如何使 WPF Slider Thumb 从任意点跟随光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的滑块:

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

我想做下一个行为:当 MouseDown 发生在滑块的任意一点时,Thumb 不仅会移动一次到该点,还会跟随光标直到 MouseUp 发生.

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.

推荐答案

此行为在您拖动滑块拇指本身时才会发生,这是设计使然.

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 ;-)

挂钩到 XAML 中的 MouseMove 事件:

Hook to the MouseMove event in XAML:

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

然后插入这段代码:

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;
    }
}

注意:

  • 如果滑块的边距和内边距不同,您可能需要考虑它们,我没有.
  • 这是在水平滑块上完成的.
  • 我的滑块的最小值为 0,如果最小值为负数,请务必调整计算.
  • 最后,它似乎只有在设置 IsMoveToPointEnabled 时才有效.

这篇关于如何使 WPF Slider Thumb 从任意点跟随光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)