WPF实现两个DataGrid列表的滚动条同步
实现目标:
左右两个DataGrid对比显示,希望拖动一个列表的滚动条,就把别一个列表的滚动条移动到相应位置。
主要思路是:
通过FindVisualChildren找到两个DataGrid的ScrollViewer控件,然后注册两个控件的ScrollChanged事件,只要有一个ScrollViewer的VerticalOffset值变了,就相应地修改另一个ScrollViewer的值。
示例代码:
var scroll1 = FindVisualChildren<ScrollViewer>(LeftList).First(); var scroll2 = FindVisualChildren<ScrollViewer>(RightList).First(); scroll1.ScrollChanged += (s, e) => { scroll2.ScrollToVerticalOffset(scroll1.VerticalOffset); }; scroll2.ScrollChanged += (s, e) => { scroll1.ScrollToVerticalOffset(scroll2.VerticalOffset); }; public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject { if (depObj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject child = VisualTreeHelper.GetChild(depObj, i); if (child != null && child is T chi) yield return chi; foreach (T childOfChild in FindVisualChildren<T>(child)) yield return childOfChild; } } }