How to enable horizontal scrolling with mouse?

后端 未结 6 1893
旧巷少年郎
旧巷少年郎 2021-02-01 07:54

I cannot determine how to scroll horizontally using the mouse wheel. Vertical scrolling works well automatically, but I need to scroll my content horizontally. My code looks lik

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 08:40

    I wrote an Attached Property for this purpose to reuse it on every ItemsControl containing an ScrollViewer. FindChildByType is an Telerik extension but can also be found here.

     public static readonly DependencyProperty UseHorizontalScrollingProperty = DependencyProperty.RegisterAttached(
                "UseHorizontalScrolling", typeof(bool), typeof(ScrollViewerHelper), new PropertyMetadata(default(bool), UseHorizontalScrollingChangedCallback));
    
            private static void UseHorizontalScrollingChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
            {
                ItemsControl itemsControl = dependencyObject as ItemsControl;
    
                if (itemsControl == null) throw new ArgumentException("Element is not an ItemsControl");
    
                itemsControl.PreviewMouseWheel += delegate(object sender, MouseWheelEventArgs args)
                {
                    ScrollViewer scrollViewer = itemsControl.FindChildByType();
    
                    if (scrollViewer == null) return;
    
                    if (args.Delta < 0)
                    {
                        scrollViewer.LineRight();
                    }
                    else
                    {
                        scrollViewer.LineLeft();
                    }
                };
            }
    
    
            public static void SetUseHorizontalScrolling(ItemsControl element, bool value)
            {
                element.SetValue(UseHorizontalScrollingProperty, value);
            }
    
            public static bool GetUseHorizontalScrolling(ItemsControl element)
            {
                return (bool)element.GetValue(UseHorizontalScrollingProperty);
            }
    

提交回复
热议问题