WPF/MVVM: Sync scrolling of two datagrids in different views

后端 未结 4 984
后悔当初
后悔当初 2021-02-09 02:03

I have two datagrids side by side bound to different data tables and each with their own view.

The datatables both have the same number of rows, and I want both grids to

4条回答
  •  独厮守ぢ
    2021-02-09 02:11

    The best way I've used so far is to use the VisualTreeHelper class to find the correct ScrollViewer object (grid or no grid). I've used this in several projects.

    Try this if any of you need it:

    private static bool ScrollToOffset(DependencyObject n, double offset)
    {
        bool terminate = false;
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(n); i++)
        {
            var child = VisualTreeHelper.GetChild(n, i);
            if (child is ScrollViewer)
            {
                (child as ScrollViewer).ScrollToVerticalOffset(offset);
                return true;
            }
        }
        if (!terminate)
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(n); i++)
                terminate = ScrollToOffset(VisualTreeHelper.GetChild(n, i), offset);
         return false;
    }
    

    Note: I typically use ListBox classes and would pass it directly to this function.

    Happy programming :)

提交回复
热议问题