有没有办法获得DataGrid中所有单元格的可迭代集合,无论它们是否被选中
答案 0 :(得分:3)
如果您的意思是DataGridCell
,则可以使用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,您将获得所有DataGridCell的列表,如下所示:
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));
}
}
答案 1 :(得分: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();
它可以帮助您避免编写循环。
答案 2 :(得分:1)
要修复该行引发的错误...
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>
(rowContainer);
添加此例程:
private T GetVisualChild<T>(DataGridRow rowContainer)
{
throw new NotImplementedException();
}