3

我有一个DataGrid取决于屏幕分辨率的可变尺寸。我需要知道用户可以看到多少行。这是我的代码:

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

我正在使用以下代码来测试变量:

MessageBox.Show(String.Format("{0} of {1} rows visible", VisibleRows, TicketGrid.Items.Count));
  • 当网格中没有行时,它会正确显示0 行中的 0 行可见

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

  • 当网格中有 9 行时,它正确显示9 行中的 9 行可见

  • 下一行是“半可见的”,所以我将其视为正确的 10 行中的 10 行:

  • 但是,要添加的下一行显然是可见的,错误地显示了 11 行中的 11 行可见

  • 在此之后添加的行是正确的(除杂散 1 之外),例如18 行中的 11 行可见


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

我怎样才能解决这个问题?

4

1 回答 1

5

这是最终对我有用的方法:

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 个可见的 9 个。“半可见”行 10 导致9 of 10 visible。对于我的目的而言,实际上最好不要将其视为可见行,所以这对我有用!:)

注意:如果您在使用 的情况下重用我的代码break,则违规行之后的任何不可见行都会抛出NullRefException.

于 2014-12-18T15:28:58.173 回答