Slider滑动条连续滑动

记录一个问题,在此感谢同事( 拚忘 - 博客园 )提供的编码方案

问题:如下图所示 需要支持触控(或鼠标)按压在1上支持滑动操作,目前仅仅在2上可以滑动操作,1上只能点击操作无法滑动。 

1 Slider滑动条支持拖动,需要将move事件转换触发PreviewMouseLeftButtonDownEvent事件模拟滑动操作。 

2 捕捉设备,锁定在当前Slider上

解决方案:

第一步 创建SliderAttach

 public static class SliderAttach
    {
        public static bool GetMoveToPointOnDrag(DependencyObject obj) { return (bool)obj.GetValue(MoveToPointOnDragProperty); }
        public static void SetMoveToPointOnDrag(DependencyObject obj, bool value) { obj.SetValue(MoveToPointOnDragProperty, value); }

        /// <summary>
        /// 滚动条点击拖动附加属性
        /// </summary>
        public static readonly DependencyProperty MoveToPointOnDragProperty = DependencyProperty.RegisterAttached("MoveToPointOnDrag", typeof(bool), typeof(SliderAttach), new PropertyMetadata
        {
            PropertyChangedCallback = (obj, changeEvent) =>
            {
                var isDown = false;
                if (!(bool)changeEvent.NewValue) return;
                var slider = (Slider)obj;
                if (!(slider.Parent is FrameworkElement parent)) return;

                parent.PreviewMouseDown += (sender, args) => { isDown = true; };
                slider.MouseMove += (obj2, mouseEvent) =>
                {
                    if (mouseEvent.LeftButton != MouseButtonState.Pressed || !isDown) return;
                    if (!slider.IsMouseCaptured) slider.CaptureMouse();
                    slider.RaiseEvent(new MouseButtonEventArgs(mouseEvent.MouseDevice, mouseEvent.Timestamp, MouseButton.Left)
                    {
                        RoutedEvent = UIElement.PreviewMouseLeftButtonDownEvent,
                        Source = mouseEvent.Source,
                    });
                };
                parent.PreviewMouseUp += (sender, args) =>
                {
                    isDown = false;
                    slider.ReleaseMouseCapture();
                };
            }
        });
    }

第二步: Slider 设置附件属性

 <Slider  resources:SliderAttach.MoveToPointOnDrag="True"/>

 

posted on 2022-05-15 11:21  TanZhiWei  阅读(114)  评论(0编辑  收藏  举报