Visible rows in the DataGrid are disabled by 1 (calculated using ContainerFromItem)

I have DataGridvariable sizes depending on the screen. I need to know how many rows are available to the user. Here is my code:

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 && Row.IsVisible) {
        VisibleRows++;
    }
}

I use the following code to check vars:

MessageBox.Show(String.Format("{0} of {1} rows visible", VisibleRows, TicketGrid.Items.Count));
  • When there are no rows in the grid, it correctly shows 0 out of 0 rows:

  • When the grid has 1 row, it correctly shows 1 out of 1 row:

  • When the grid has 9 lines, it correctly displays 9 of 9 lines:

  • The next line is half-hearted, so I will assume that it shows 10 out of 10 lines, visible as correct:

  • However, the next line to be added is visible, apparently 11 out of 11 lines are displayed incorrectly:

  • The lines added after that are correct (byte-wandering 1), for example. 11 of 18 lines:


- 1, , . > 10, .

?

+3
1

, , :

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) {
        /*
           This is the magic line! We measure the Y position of the Row, relative to
           the TicketGrid, adding the Row height. If it exceeds the height of the
           TicketGrid, it ain't visible!
        */

        if(Row.TransformToVisual(TicketGrid).Transform(new Point(0, 0)).Y + Row.ActualHeight >= TicketGrid.ActualHeight) {
            break;
        }

        VisibleRows++;
    }
}

9 9 9 . "" 10 9 10 . , , !:)

: break, - NullRefException.

+5

All Articles