2

有没有办法获取 DataGrid 中所有单元格的可迭代集合,无论它们是否被选中

4

3 回答 3

3

如果您的意思是DataGridCells,您可以使用 Vincent Sibals 辅助函数来遍历所有行DataGrid.Items和列DataGrid.Columns

public DataGridCell GetCell(int row, int column)
{
    DataGridRow rowContainer = GetRow(row);

    if (rowContainer != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

        // try to get the cell but it may possibly be virtualized
        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        if (cell == null)
        {
            // now try to bring into view and retreive the cell
            DataGrid_Standard.ScrollIntoView(rowContainer, DataGrid_Standard.Columns[column]);
            cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        }
        return cell;
    }
    return null;
}

public DataGridRow GetRow(int index)
{
    DataGridRow row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // may be virtualized, bring into view and try again
        DataGrid_Standard.ScrollIntoView(DataGrid_Standard.Items[index]);
        row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

编辑

如果 grid 是您的 DataGrid,您将获得所有 DataGridCells 的列表,如下所示:

List<DataGridCell> allCellList = new List<DataGridCell>();

for (int i = 0; i < grid.Items.Count; i++)
{
    for (int j = 0; j < grid.Columns.Count; j++)
    {
        allCellList.Add(grid.GetCell(i, j));
    }
}
于 2012-07-23T15:33:48.803 回答
1

为了方便(不一定是性能),您可以将DataGrid中的数据(包括所有列和行的所有单元格)填充到单个DataTable中,它提供了帮助操作数据的功能,例如迭代、过滤、排序等.

// Populate a DataGrid to a DataTable
DataTable dt; 
DataView dv = (DataView) myDataGrid.DataSource;
dt = dv.Table.DataSet.Tables[0];

随后,您可以在短短一行代码中使用泛型将任何特定列转换为集合或列表。请参阅how-do-you-convert-a-datatable-into-a-generic-list

List<DataRow> myList = dt.Rows.Cast<DataRow>().ToList();

它使您免于编写循环。

于 2012-07-24T00:30:07.717 回答
1

要修复该行引发的错误...

    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter> 
        (rowContainer);

添加此例程:

private T GetVisualChild<T>(DataGridRow rowContainer)
    {
        throw new NotImplementedException();
    }
于 2018-09-19T16:14:14.083 回答