使用模板不容易实现这一点,因为鼠标位置不是依赖属性,鼠标移动不是路由事件。这真的归结为您想要做什么,如果只是显示一条垂直线是否鼠标,那么我同意 Dany 使用装饰器,因为您对滑块本身并不真正感兴趣。但是,如果要将拇指移动到鼠标所在的位置,我会使用附加属性。
我使用附加属性而不是直接在控件上连接事件的原因是它提供了更多模块化和可重用的代码库,并使其在 XAML 中的视觉效果更加明显,而不是需要将 C# 代码视为好吧。
这是我的建议
public class SliderHelperPackage
{
public static readonly DependencyProperty BindThumbToMouseProperty = DependencyProperty.RegisterAttached(
"BindThumbToMouse", typeof(bool), typeof(SliderHelperPackage), new PropertyMetadata(false, OnBindThumbToMouseChanged));
public static void SetBindThumbToMouse(UIElement element, bool value)
{
element.SetValue(BindThumbToMouseProperty, value);
}
public static bool GetBindThumbToMouse(UIElement element)
{
return (bool)element.GetValue(BindThumbToMouseProperty);
}
private static void OnBindThumbToMouseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue.Equals(e.OldValue))
return;
var slider = d as Slider;
if (slider == null)
throw new ArgumentException(@"dependency object must be a slider", "d");
if ((bool) e.NewValue)
{
slider.MouseMove += SliderMouseMove;
}
else
{
slider.MouseMove -= SliderMouseMove;
}
}
static void SliderMouseMove(object sender, MouseEventArgs e)
{
var slider = (Slider) sender;
var position = e.GetPosition(slider);
// When the mouse moves, we update the slider's value so it's where the ticker is (we take into account margin's on the track)
slider.Value = (slider.Maximum - slider.Minimum)*Math.Max(position.X-5,0)/(slider.ActualWidth-10) + slider.Minimum;
}
}
然后您可以像这样在您的 XAML 中使用它。因此,当您将此设置为 true 时,我们会连接到滑块上的鼠标移动事件并更改其值,以便拇指跟随鼠标
<Slider SliderPosn:SliderHelperPackage.BindThumbToMouse="True" Margin="5" Height="25" VerticalAlignment="Top"/>