Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing scroll positions for 2 WPF DataGrids

I am trying to synchronize the horizontal scroll position of 2 WPF DataGrid controls.

I am subscribing to the ScrollChanged event of the first DataGrid:

<toolkit:DataGrid x:Name="SourceGrid" ScrollViewer.ScrollChanged="SourceGrid_ScrollChanged">

I have a second DataGrid:

<toolkit:DataGrid x:Name="TargetGrid">

In the event handler I was attempting to use the IScrollInfo.SetHorizontalOffset, but alas, DataGrid doesn't expose IScrollInfo:

private void SourceGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
    ((IScrollInfo)TargetGrid).SetHorizontalOffset(e.HorizontalOffset);
    // cast to IScrollInfo fails
}

Is there another way to accomplish this? Or is there another element on TargetGrid that exposes the necessary IScrollInfo to achieve the synchronization of the scroll positions?

BTW, I am using frozen columns, so I cannot wrap both DataGrid controls with ScrollViewers.

like image 854
Philipp Schmid Avatar asked Nov 16 '08 00:11

Philipp Schmid


3 Answers

There is great piece of code to do this:

http://www.codeproject.com/KB/WPF/ScrollSynchronization.aspx

like image 51
greenoldman Avatar answered Sep 19 '22 01:09

greenoldman


According to the Microsoft product group, traversing the visual tree to find the ScrollViewer is the recommended method, as explained in their answer on Codeplex.

like image 45
Philipp Schmid Avatar answered Sep 20 '22 01:09

Philipp Schmid


We had this same problem when using the Infragistics grid because it didn't (still doesn't) support frozen columns. So we had two grids side-by-side that were made to look as one. The grid on the left didn't scroll horizontally but the grid on the right did. Poor man's frozen columns.

Anyway, we ended up just reaching into the visual tree and pulling out the ScrollViewer ourselves. Afterall, we knew it was there - it just wasn't exposed by the object model. You could use a similar approach if the WPF grid does not expose the ScrollViewer. Or you could subclass the grid and add the functionality you require to make this work.

Interested in hearing why you need to do this.

like image 36
Kent Boogaart Avatar answered Sep 20 '22 01:09

Kent Boogaart