Count the number of visible rows in a DataGrid

I would like to know how many lines WPF actually displays DataGrid.

I tried to loop DataGridRowand checked IsVisible, but it seems that the lines are reporting IsVisible = trueeven if they are not in the viewport DataGrid.

How to correctly calculate the number of visible lines?

+5
source share
3 answers

I asked this question also on the 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);
}
+1
source

I had the same problem with lines that seemed like Visible = trueeven when they weren't.

, : DataGrid 1 ( ContainerFromItem).

:

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++;
    }
}

/* comments */, , .

+1

a simple hack comes to mind

iterate over all the lines and check if the container has a container?

dataGrid.GetContainerFromItem(dataGrid.Items[row]);

hope this helps

0
source

All Articles