Search code examples
c#.netwpfscrollviewer

Synchronized scrolling of two ScrollViewers whenever any one is scrolled in wpf


I have gone through the thread:

binding two VerticalScrollBars one to another

it has almost helped to achieve the goal but still there is something missing. It is that moving the scrollbars left-right or up-down gives expected behavior of scrolling in both of my scrollviewers but when we try to scroll using/clicking arrow buttons at the ends of these scrollbars in scrollviewers only one scrollviewer is scrolled which is not the expected behavior.

So what else we need to add/edit to solve this?


Solution

  • One way to do this is using the ScrollChanged event to update the other ScrollViewer

    <ScrollViewer Name="sv1" Height="100" 
                  HorizontalScrollBarVisibility="Auto"
                  ScrollChanged="ScrollChanged">
        <Grid Height="1000" Width="1000" Background="Green" />
    </ScrollViewer>
    
    <ScrollViewer Name="sv2" Height="100" 
                  HorizontalScrollBarVisibility="Auto"
                  ScrollChanged="ScrollChanged">
        <Grid Height="1000" Width="1000" Background="Blue" />
    </ScrollViewer>
    
    private void ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (sender == sv1)
            {
                sv2.ScrollToVerticalOffset(e.VerticalOffset);
                sv2.ScrollToHorizontalOffset(e.HorizontalOffset);
            }
            else
            {
                sv1.ScrollToVerticalOffset(e.VerticalOffset);
                sv1.ScrollToHorizontalOffset(e.HorizontalOffset);
            }
        }