【问题标题】:Count the number of visible rows in a DataGrid计算 DataGrid 中的可见行数
【发布时间】:2011-08-24 04:52:06
【问题描述】:

我想知道 WPF DataGrid 实际显示了多少行。

我尝试循环遍历DataGridRow 并检查IsVisible,但似乎行报告IsVisible = true,即使它们不在DataGrid 视口中。

如何正确计算可见行数?

【问题讨论】:

    标签: c# .net wpf datagrid .net-4.0


    【解决方案1】:

    我也在 MSDN 论坛上问过这个问题,得到了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);
    }
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,行显示为 Visible = true,即使它们不是。

      为了想出一个解决方案,我发布了这个问题:Visible rows in DataGrid is off by 1 (counted using ContainerFromItem)

      这对我有用:

      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) {
              if(Row.TransformToVisual(TicketGrid).Transform(new Point(0, 0)).Y + Row.ActualHeight >= TicketGrid.ActualHeight) {
                  break;
              }
      
              VisibleRows++;
          }
      }
      

      为了获得进一步的指导,我对链接问题的回答中有一些 /* comments */,以及导致答案的问题本身的用户 cmets 线程。

      【讨论】:

        【解决方案3】:

        想到一个简单的技巧,

        遍历所有行并检查项目是否有容器?

        dataGrid.GetContainerFromItem(dataGrid.Items[row]);
        

        希望对你有帮助

        【讨论】:

        • 这不起作用。事实上,在我的循环中,我使用了ItemContainerGenerator.ContainerFromIndex,一些未显示的项目仍然有容器。
        【解决方案4】:

        如果您需要它用于另一个 xaml 元素,只需通过“ElementName”将引用和通过“Items.Count”的属性添加到您的内容属性(在本例中为“文本”)。您还可以使用转换器来解析该值。

        <TextBlock Text="{Binding ElementName=ComponentDataGrid, Path=Items.Count, Converter={StaticResource IntToStringConverter}}"/>
        

        【讨论】:

          猜你喜欢
          • 2014-10-30
          • 2015-02-17
          • 1970-01-01
          • 2010-10-14
          • 2019-12-05
          • 1970-01-01
          • 1970-01-01
          • 2010-10-24
          • 1970-01-01
          相关资源
          最近更新 更多