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

前端 未结 5 1753
长情又很酷
长情又很酷 2020-11-27 05:48

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.

5条回答
  •  無奈伤痛
    2020-11-27 06:26

    The question is for WPF, but in case anyone developing UWP stumbles upon this, I had to take a slightly different approach.
    In UWP, when you set the scroll offset of the other scroll viewer (using ScrollViewer.ChangeView), it also triggers the ViewChanged event on the other scroll viewer, basically creating a loop, causing it to be very stuttery, and not work properly.

    I resolved this by using a little time-out on handling the event, if the object being scrolled is not equal to the last object that handled the event.

    XAML:

     ... 
     ... 
    

    Code behind:

    public sealed partial class MainPage
    {
        private const int ScrollLoopbackTimeout = 500;
    
        private object _lastScrollingElement;
        private int _lastScrollChange = Environment.TickCount;
    
        public SongMixerUserControl()
        {
            InitializeComponent();
        }
    
        private void SynchronizedScrollerOnViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (_lastScrollingElement != sender && Environment.TickCount - _lastScrollChange < ScrollLoopbackTimeout) return;
    
            _lastScrollingElement = sender;
            _lastScrollChange = Environment.TickCount;
    
            ScrollViewer sourceScrollViewer;
            ScrollViewer targetScrollViewer;
            if (sender == ScrollViewer1)
            {
                sourceScrollViewer = ScrollViewer1;
                targetScrollViewer = ScrollViewer2;
            }
            else
            {
                sourceScrollViewer = ScrollViewer2;
                targetScrollViewer = ScrollViewer1;
            }
    
            targetScrollViewer.ChangeView(null, sourceScrollViewer.VerticalOffset, null);
        }
    }
    

    Note that the timeout is 500ms. This may seem a little long, but as UWP apps have an animation (or, easing, really) in their scrolling (when using the scroll wheel on a mouse), it causes the event to trigger for a few times within a few hundred milliseconds. This timeout seems to work perfectly.

提交回复
热议问题