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

前端 未结 10 1611
醉话见心
醉话见心 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 18:54

    An improvement to Don B's solution is to avoid using ScrollToVerticalOffset.

    scv.ScrollToVerticalOffset(scv.VerticalOffset - e.Delta);
    

    VerticalOffset - Delta results in a pretty jarring experience. The ScrollViewer puts a lot of thought into making the movement smoother than that. I think it also scales the delta down based on dpi and other factors...

    I found it's better to catch and handle the PreviewMouseWheelEvent and send a MouseWheelEvent to the intended ScrollViewer. My version of Don B's solution looks like this.

    private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
    {
        var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
        eventArg.RoutedEvent = UIElement.MouseWheelEvent;
        eventArg.Source = e.Source;
    
        ScrollViewer scv = (ScrollViewer)sender;
        scv.RaiseEvent(eventArg);
        e.Handled = true;
    }
    

提交回复
热议问题