Check visible rows in a WPF DataGrid
Solution 1
How about subscribing to the ScrollViewer.ScrollChanged event on the DataGrid's ScrollViewer? The event arguments for it are pretty extensive, describing how much the ScrollViewer moved and what its new Vertical offset is. Also, according to MSDN:
If CanContentScroll is true, the values of the ExtentHeight, ScrollableHeight, ViewportHeight, and VerticalOffset properties are number of items. If CanContentScroll is false, the values of these properties are Device Independent Pixels.
CanContentScroll is indeed the case for the ScrollViewer for a DataGrid.
All you have to do is find the ScrollViewer:
ScrollViewer scrollview = FindVisualChild<ScrollViewer>(dataGrid);
using an implementation of FindVisualChild that can be found in various places (like here: Finding control within WPF itemscontrol).
Solution 2
Detecting scrolling is as easy as
<DataGrid ScrollViewer.ScrollChanged="DataGrid_ScrollChanged" />
Now you must get ScrollViewer instance:
void DataGrid_ScrollChanged(object sender, RoutedEventArgs e)
{
var scroll = FindVisualChild<ScrollViewer>((DependencyObject)sender);
...
}
(Not sure where is origin of FindVisualChild, but there are plenty of implementations, e.g. here)
And then you can
int firstRow = (int)scroll.VerticalOffset;
int lastRow = (int)scroll.VerticalOffset + (int)scroll.ViewportHeight + 1;
Comments
-
ctrlalt313373 about 2 years
I have a WPF
DataGrid
, which when there are too many rows to view on the screen it gets a vertical scrollbar. What I would like to know is if there is a way to know what the top visible row is when the user is scrolling.Ideally I would like to be able to wire up an event to know when the user is scrolling and on scroll, check what the top visible row is in order to update some information.
-
ctrlalt313373 over 15 yearsThanks. I've gotten around it by just scaling up what is in the grid (fonts mainly) using animations. Not quite as simple, but basically what I wanted.
-
ctrlalt313373 over 15 yearsI ran into an issue with scaling the font, that when scaling the font down the columns won't auto resize so they are still width of the bigger font size.
-
Bob King over 15 yearsThere's sadly a bug in the current build of the WPFToolkit that makes auto resize columns work strangely when they're mixed with Star sized columns. We see that behavior as well, and we've just never bothered to fix it.
-
ctrlalt313373 over 15 yearsThanks, actually if my above comments make no sense it was because I've been working on two separate issues, one with trying to figure out the top row and the other with zooming a datagrid. I gave up on the top row thing and told the user they would need to adjust the UI.
-
Gerard almost 9 yearsThis is actually a nice and solid approach.
-
Parisa almost 6 yearsThe correct index of the last row is calculated using (int)scroll.VerticalOffset + (int)scroll.ViewportHeight - 1;