views:

2355

answers:

2

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.

+1  A: 

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.

HTH, Kent

Kent Boogaart
I have source for the WPF Toolkit DataGrid from Codeplex, so I might be able to find it and expose it (not my preferred method). I am stacking 2 grids to get the frozen pane effect (ala Excel).
Philipp Schmid
+1  A: 

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.

Philipp Schmid
Yeah. I've done the same thing the same way in the past, though. It just seems like we shouldn't have to hack through the visual tree this way. Just another way that WPF is rough around the edges.
PeterAllenWebb
Be careful when the user changes visual themes - controls then get new templates (= new visual trees), and you will be holding reference to a wrong scrollviewer. You should react in OnApplyTemplate, and look-up the actual ScrollViewer every time it is invoked. See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.onapplytemplate.aspx
Tomáš Kafka