I have a data grid:
<DataGrid x:Name="Foo" ... />
I’d like to bind an element’s height to the height of the data grid. Simply doing {Binding ElementName=Foo, Path=ActualHeight} will not work, because it takes the ScrollViewer‘s height, not the total height of the data grid’s contents.
You need to find the DataGrid’s internal
ScrollViewer, and bind to it’sViewportHeightDepending 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:
I can’t remember if there’s more than one
ScrollViewerin aDataGrid… 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 theDataGridto a Converter, and have it find theScrollViewerandViewportHeightin the ConverterEdit
I actually did a few tests, and the DataGrid’s
ScrollViewertreats sizes a bit differently, probably due toVirtualization. It appears to use relative sizes based on the number of rows.The test
DataGridI was working with had 23 rows. TheScrollViewer.ExtentHeightwas equal to 23, andScrollViewer.ViewportHeightwas 3, meaning there were 23 rows total, and 3 complete rows were being shown. TheScrollViewer.ScrollableHeightwas 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 theScrollViewer.VerticalOffsetwas 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 theActualHeightof one of the visible rows, and multiply it by theScrollViewer.ExtentHeightto get the actual size of your content. This will only work if theHeightof all your items is the same though.