在DataGrid中可见行是关闭的1(使用ContainerFromItem计)DataGrid、ContainerFromItem

2023-09-03 21:35:16 作者:手心张开来呼吸自由的空气

我有可变的尺寸取决于屏幕清晰度的的DataGrid 。我需要知道有多少行是对用户可见。这是我的code:

I have a DataGrid of variable dimensions dependent upon screen-res. I need to know how many rows are visible to the user. Here's 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++;
    }
}

我用下面的code测试瓦尔:

I'm using the following code to test the vars:

MessageBox.Show(String.Format("{0} of {1} rows visible", VisibleRows, TicketGrid.Items.Count));

当有在电网无行,它显示正确的 0 0的行可见的:

When there are no rows in the grid, it correctly shows 0 of 0 rows visible:

当有1行中的网格,它正确地显示的 1的行可见的:

当有网格9行,它显示正确的 9 9行可见的:

在接下来的行是半看得见的,所以我会指望它呈现出的 10 10的行可见的是正确的: The next row is "half-visible", so I'll count it showing 10 of 10 rows visible as correct:

然而待加入的下一行是显然可见的,不正确地表示的 11 11的行可见的

在此添加的行是正确的(酒吧杂散1),例如: 11月18日的行可见的:

我不能 - 1 ,因为它只有一定数量的已被添加之后不正确。我无法检查> 10 ,因为尺寸是可变的。

I can't just - 1, because it's only incorrect after a certain number have been added. I can't check > 10, because the dimensions are variable.

我该如何解决这个问题?

How can I fix this?

推荐答案

下面是最终为我工作:

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's 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的可见的。这是我的目的,其实更好的为这个不会可以算作一个可见行,所以这会为我做的! :)

Upto and including row 9 shows 9 of 9 visible. The "half-visible" row 10 results in 9 of 10 visible. It's actually better for my purposes for this not to count as a visible row, so this'll do for me! :)

请注意:如果你打算重用我的code的没有的使用破发,违规行之后的任何无形的行会抛出一个 NullRefException

Note: if you're reusing my code without using the break, any invisible rows after the offending row will throw a NullRefException.