效果:兩個DataGrid的滾動條實現同步滾動。 代碼參考了博客園chuncn的文章《.net中同步多個ScrollViewer滾動的四種方法》,原文是針對ListBox的。現改為針對DataGrid,略微作了修改,代碼以水平滾動條為例。 原文地址:https://www.cnblogs.com/c ...
效果:兩個DataGrid的滾動條實現同步滾動。
代碼參考了博客園chuncn的文章《.net中同步多個ScrollViewer滾動的四種方法》,原文是針對ListBox的。現改為針對DataGrid,略微作了修改,代碼以水平滾動條為例。
原文地址:https://www.cnblogs.com/chuncn/archive/2011/10/08/2202175.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的ScrollViewer sv1 = 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); }