Mouse scroll not working in a scroll viewer with a wpf datagrid and additional UI elements

前端 未结 10 1416
醉话见心
醉话见心 2021-02-03 18:41

I am trying to figure out how to get the mouse scroll working on a wpf window with a scrollviewer and a datagrid within it. The WPF and C# code is below



        
10条回答
  •  一生所求
    2021-02-03 19:00

    To enable touch support you might also want to set ScrollViewer.PanningMode to None on your DataGrid and set the same property to VerticalFirst or other value on your top level ScrollViewer

    Example

    
        
    
    

    Of course, also use the PreviewMouseWheel event as indicated by Don B's answers to fix the original mouse scrolling issue.

    private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
    {
        var scrollViewer = (ScrollViewer)sender;
        scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
        e.Handled = true;
    }
    

    Or, you can simply set the following Attached Property to your ScrollViewer

    public class TopMouseScrollPriorityBehavior
    {
        public static bool GetTopMouseScrollPriority(ScrollViewer obj)
        {
            return (bool)obj.GetValue(TopMouseScrollPriorityProperty);
        }
    
        public static void SetTopMouseScrollPriority(ScrollViewer obj, bool value)
        {
            obj.SetValue(TopMouseScrollPriorityProperty, value);
        }
    
        public static readonly DependencyProperty TopMouseScrollPriorityProperty =
            DependencyProperty.RegisterAttached("TopMouseScrollPriority", typeof(bool), typeof(TopMouseScrollPriorityBehavior), new PropertyMetadata(false, OnPropertyChanged));
    
        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var scrollViewer = d as ScrollViewer;
            if (scrollViewer == null)
                throw new InvalidOperationException($"{nameof(TopMouseScrollPriorityBehavior)}.{nameof(TopMouseScrollPriorityProperty)} can only be applied to controls of type {nameof(ScrollViewer)}");
            if (e.NewValue == e.OldValue)
                return;
            if ((bool)e.NewValue)
                scrollViewer.PreviewMouseWheel += ScrollViewer_PreviewMouseWheel;
            else
                scrollViewer.PreviewMouseWheel -= ScrollViewer_PreviewMouseWheel;
        }
    
        private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            var scrollViewer = (ScrollViewer)sender;
            scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
            e.Handled = true;
        }
    }
    

    Usage

    
        
    
    

    Where b: is the namespace that contains this behavior

    This way your no code-behind is needed and your app is purely MVVM

提交回复
热议问题