Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of visible rows in a DataGrid

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?

like image 605
Amir Gonnen Avatar asked May 12 '11 14:05

Amir Gonnen


2 Answers

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);
}
like image 56
Amir Gonnen Avatar answered Sep 30 '22 11:09

Amir Gonnen


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.

like image 29
Danny Beckett Avatar answered Sep 30 '22 11:09

Danny Beckett