【问题标题】:Visible rows in DataGrid is off by 1 (counted using ContainerFromItem)DataGrid 中的可见行减 1(使用 ContainerFromItem 计数)
【发布时间】:2015-02-17 08:17:24
【问题描述】:

我有一个 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,因为尺寸是可变的。

我该如何解决这个问题?

【问题讨论】:

  • 半可见行之后的行可见
  • @DrKoch 这就是重点......
  • 您的文字说“显然可见” - 非常混乱
  • @DrKoch C# 说它是可见的;不是。它“显然”可见,但很抱歉造成混淆! :)
  • 我找到了解决方案!现在就编码吧! :)

标签: c# .net wpf datagrid off-by-one


【解决方案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'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 个可见,共 10 个。对于我的目的来说,将这个 not 算作可见行实际上更好,所以这对我有用! :)

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

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 2014-10-30
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    相关资源
    最近更新 更多