Search code examples
c#wpfdatagridscrollviewerattached-properties

Wpf. Scroll DataGrid inside ScrollViewer


Current realization

Hello there. Currently I have the following application:

enter image description here

If you can see, when my cursor on blue or red zone I`am scrolling only the main ScrollViewer.

Expectations

I'am expecting that if I'll scroll with cursor on DataGrid, should be scrolled only the DataGrid. Not the main ScrollViewer. But currently it works like the following demo:

enter image description here

Question

How can I enable the possibility to scroll DataGrid at ScrollViewer?

Current code

<ScrollViewer x:Name="ScrollViewer" PanningMode="Both" Background="Blue"
                HorizontalScrollBarVisibility="Auto" Padding="0,0,50,0"
                VerticalScrollBarVisibility="Auto" PreviewMouseWheel="DataGrid_PreviewMouseWheel">

    <StackPanel>
        <DataGrid x:Name="DataGrid0" ItemsSource="{Binding Items}" Height="300"
                    AutoGenerateColumns="True" PreviewMouseWheel="DataGrid_PreviewMouseWheel"
                    HorizontalScrollBarVisibility="Auto"
                    VerticalScrollBarVisibility="Auto"/>
        <Rectangle Height="200" Fill="Red"/>
        <DataGrid x:Name="DataGrid1" ItemsSource="{Binding Items}" Height="300"
                    AutoGenerateColumns="True" PreviewMouseWheel="DataGrid_PreviewMouseWheel"
                    HorizontalScrollBarVisibility="Auto"
                    VerticalScrollBarVisibility="Auto"/>
    </StackPanel>

</ScrollViewer>
private void DataGrid_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
{
    var args = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
    args.RoutedEvent = ScrollViewer.MouseWheelEvent;

    if (e.Source is DataGrid)
    {
        DataGrid0.RaiseEvent(args);
    }
    else
    {
        ScrollViewer.RaiseEvent(args);
    }
}

Solution

  • Remove PreviewMouseWheel event from Scrollviewer and DataGrid too.