查找当前显示在 DataGrid 中的第一个和最后一个项目的索引

Finding indexes of first and last items currently displayed in DataGrid

在我的 DataGrid 中,我想找到当前显示的第一个和最后一个项目索引。这不像处理普通的旧 ListBox 和 Scrollviewer 那样容易。

有人能告诉我怎么做吗?

您可以遍历 ItemSource 并获取第一个和最后一个 DataGridRow。这不是一个好的解决方案,但你可以这样尝试。

DataGridRow firstRow = null;
DataGridRow lastRow = null;
for (int i = 0; i < dataGrid.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
    if (row != null)
    {
        firstRow = row;
        while (row != null)
        {
            row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(++i);
        }
        lastRow = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i - 1);
        break;
    }
}