页面代码
<Grid DockPanel.Dock="Left" Width="400"> <DataGrid Name="dgSource" VerticalScrollBarVisibility="Visible" EnableRowVirtualization="False" ScrollViewer.ScrollChanged="DgSource_ScrollChanged" > </DataGrid> </Grid> <Grid> <DataGrid Name="dgTo" VerticalScrollBarVisibility="Visible" EnableRowVirtualization="False" ScrollViewer.ScrollChanged="DgTo_ScrollChanged"> </DataGrid> </Grid>
后端代码
1 private void DgTo_ScrollChanged(object sender, ScrollChangedEventArgs e) 2 { 3 ScrollChanged(dgTo, dgSource, e); 4 } 5 6 void ScrollChanged(DataGrid dg1, DataGrid dg2, ScrollChangedEventArgs e) 7 { 8 if (e.HorizontalChange != 0.0f) 9 { 10 ScrollViewer sv = null; 11 Type t = dg1.GetType(); 12 try 13 { 14 sv = t.InvokeMember("InternalScrollHost", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, dg2, null) as ScrollViewer; 15 sv.ScrollToHorizontalOffset(e.HorizontalOffset); 16 } 17 catch (Exception ex) 18 { 19 MessageBox.Show(ex.Message); 20 } 21 } 22 if (e.VerticalChange != 0.0f) 23 { 24 ScrollViewer sv = null; 25 Type t = dg1.GetType(); 26 try 27 { 28 sv = t.InvokeMember("InternalScrollHost", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, dg2, null) as ScrollViewer; 29 sv.ScrollToVerticalOffset(e.VerticalOffset); 30 } 31 catch (Exception ex) 32 { 33 MessageBox.Show(ex.Message); 34 } 35 } 36 37 } 38 39 private void DgSource_ScrollChanged(object sender, ScrollChangedEventArgs e) 40 { 41 ScrollChanged(dgSource, dgTo, e); 42 }