I would like to know how many rows are actually displayed by a WPF DataGrid
.
I tried looping over DataGridRow
and checking IsVisible
, but it seems that rows report IsVisible = true
even when they are not in the DataGrid
viewport.
How can I count the number of visible rows correctly?
I've asked this question also on MSDN forum and got a good answer:
private bool IsUserVisible(FrameworkElement element, FrameworkElement container) {
if (!element.IsVisible)
return false;
Rect bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
Rect rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);
}
I had the same problem with rows showing as Visible = true
even when they weren't.
Trying to come up with a solution, I posted this question: Visible rows in DataGrid is off by 1 (counted using ContainerFromItem).
Here's what worked for me:
uint VisibleRows = 0;
var TicketGrid = (DataGrid) MyWindow.FindName("TicketGrid");
foreach(var Item in TicketGrid.Items) {
var Row = (DataGridRow) TicketGrid.ItemContainerGenerator.ContainerFromItem(Item);
if(Row != null) {
if(Row.TransformToVisual(TicketGrid).Transform(new Point(0, 0)).Y + Row.ActualHeight >= TicketGrid.ActualHeight) {
break;
}
VisibleRows++;
}
}
For further guidance, there are some /* comments */
in my answer on the linked question, as well as a thread of user comments on the question itself that led to the answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With