You need to find the DataGrid's internal ScrollViewer
, and bind to it's ViewportHeight
Depending on what you're doing with this value and where you need it, this can be done in a variety of ways.
Typically this sort of thing is needed for a View-Only purpose, so I would put the code to find the ViewPort height in the CodeBehind
For example, using some VisualTreeHelpers, you could do something like this:
// Find first child of type ScrollViewer in object Foo
var scrollViewer = VisualTreeHelpers.FindChild<ScrollViewer>(Foo);
// If object is found, set other control's height to ViewportHeight
if (scrollViewer != null)
{
MyControl.Height = scrollViewer.ViewportHeight;
}
I can't remember if there's more than one ScrollViewer
in a DataGrid
... you'd have to use something like Snoop to find out for sure. If there is, there's an overload of .FindChild()
to find an element by name that you should be able to use. The name can be obtained through something like Snoop too.
This could also be done in a Converter
, where you pass the DataGrid
to a Converter, and have it find the ScrollViewer
and ViewportHeight
in the Converter
<Grid Height="{Binding ElementName=Foo,
Converter={StaticResource GetDataGridContentHeight}}" />
Edit
I actually did a few tests, and the DataGrid's ScrollViewer
treats sizes a bit differently, probably due to Virtualization
. It appears to use relative sizes based on the number of rows.
The test DataGrid
I was working with had 23 rows. The ScrollViewer.ExtentHeight
was equal to 23, and ScrollViewer.ViewportHeight
was 3, meaning there were 23 rows total, and 3 complete rows were being shown. The ScrollViewer.ScrollableHeight
was equal to 20, meaning I could scroll from 0 to 20 (since 3 items are shown, it doesn't need to go to 23), and the ScrollViewer.VerticalOffset
was set to whatever item I was currently scrolled to.
So to get the actual content height of items in a virtualized ScrollViewer
, I think you're going to have to get the ActualHeight
of one of the visible rows, and multiply it by the ScrollViewer.ExtentHeight
to get the actual size of your content. This will only work if the Height
of all your items is the same though.