Synchronizing Two Rich Text Box Scroll bars in WPF

c#, scrollbar, wpf

Solution

You can use the `ScrollViewer.ScrollChanged` routed event to listen for scrolling changes. Example:

<UniformGrid Rows="1" Width="300" Height="150" >
    <RichTextBox x:Name="_rich1" 
                 VerticalScrollBarVisibility="Auto"
                 ScrollViewer.ScrollChanged="RichTextBox_ScrollChanged" />
    <RichTextBox x:Name="_rich2" 
                 VerticalScrollBarVisibility="Auto"
                 ScrollViewer.ScrollChanged="RichTextBox_ScrollChanged" />
</UniformGrid>

Then, in the event handler you do the actual synchronizing (code stolen from inspired by this other answer):

private void RichTextBox_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
    var textToSync = (sender == _rich1) ? _rich2 : _rich1;

    textToSync.ScrollToVerticalOffset(e.VerticalOffset);
    textToSync.ScrollToHorizontalOffset(e.HorizontalOffset);
}

Problem

I have researched ways of synchronizing scroll bars for rich text boxes but have only come across solutions or methods for Winforms but these do not work in WPF application. If anyone has done this in WPF and could provide some direction/code/guidance in how to go about implementing this, it will be greatly appreciated. I am new to WPF so any help is welcomed. Thanks.

Original source

Related problems