Search code examples
c#.netwpfdatagrid.net-4.0

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?


Solution

  • 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);
    }