效果
效果:两个DataGrid的滚动条实现同步滚动。
代码参考了博客园chuncn的文章《.net中同步多个ScrollViewer滚动的四种方法》,原文是针对ListBox的。现改为针对DataGrid,略微作了修改,代码以水平滚动条为例。
原文地址:/chuncn/archive//10/08/275.html
实现方法:
方法一:利用DependencyProperty类的RegisterAttached方法,在属性系统上注册附加属性,并将滚动条属性值HorizontalOffset通过注册属性关联到一个方法。
ScrollViewer sv1, sv2;private void Window_Loaded(object sender, RoutedEventArgs e){//分别获取两个DataGrid的ScrollViewer
sv1 = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.DataGrid1, 0), 0) as ScrollViewer;sv2 = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.DataGrid2, 0), 0) as ScrollViewer;//将滚动条属性值HorizontalOffset关联到OnScrollChanged1方法
var offsetChangeListener =DependencyProperty.RegisterAttached("ListenerOffset1", typeof(object), typeof(UserControl), new PropertyMetadata(OnScrollChanged1));var binding = new Binding("HorizontalOffset") { Source = sv1 };sv1.SetBinding(offsetChangeListener, binding);offsetChangeListener =DependencyProperty.RegisterAttached("ListenerOffset2", typeof(object), typeof(UserControl), new PropertyMetadata(OnScrollChanged2));binding = new Binding("HorizontalOffset") { Source = sv2 };sv2.SetBinding(offsetChangeListener, binding);}public void OnScrollChanged1(DependencyObject sender, DependencyPropertyChangedEventArgs e){double a = (double)e.NewValue; //获取滚动条位置变化后的属性值sv2.ScrollToHorizontalOffset(a);}public void OnScrollChanged2(DependencyObject sender, DependencyPropertyChangedEventArgs e){double a = (double)e.NewValue;sv1.ScrollToHorizontalOffset(a);}
方法二:利用滚动条的ScrollChanged事件,同步两个滚动条的位置。
ScrollViewer sv1, sv2;
private void Window_Loaded(object sender, RoutedEventArgs e){//分别获取两个DataGrid的ScrollViewersv1 = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.DataGrid1, 0), 0) as ScrollViewer;sv2 = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.DataGrid2, 0), 0) as ScrollViewer;//关联ScrollChanged事件sv1.ScrollChanged += new ScrollChangedEventHandler(sv1_ScrollChanged);sv2.ScrollChanged += new ScrollChangedEventHandler(sv2_ScrollChanged);}void sv1_ScrollChanged(object sender, ScrollChangedEventArgs e){sv2.ScrollToHorizontalOffset(sv1.HorizontalOffset);}void sv2_ScrollChanged(object sender, ScrollChangedEventArgs e){sv1.ScrollToHorizontalOffset(sv2.HorizontalOffset);}