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

前端 未结 10 1417
醉话见心
醉话见心 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:04

    The Grid has a built in ScrollPanel so wrapping it with a ScrollPanel didn't work at all for me (making the Grid of fixed height was out of the question because I wanted it to resize nicely with the rest of the application).

    What I did was a combination of a few of the higher rated solutions in here, but essentially the idea is to get rid of the ScrollPanel and just pipe the PreviewMouseEvent of the DataGrid back to the parent control that is actually handling the scrolling (in my case it was a Grid).

        private void DataGrid_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
    
            MouseWheelEventArgs eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
            {
                RoutedEvent = MouseWheelEvent, Source = e.Source
            };
            DependencyObject parent = VisualTreeHelper.GetParent((DependencyObject) sender);
    
            while (parent != null && !(parent is Grid))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
    
            if (parent != null)
            {
                Grid grid = (Grid) parent;
                grid.RaiseEvent(eventArg);
            }
    
            e.Handled = true;
        }
    

提交回复
热议问题