【发布时间】:2013-03-04 06:29:33
【问题描述】:
我的DataGrid 处理大量数据(平均多达 40k 行),所以我需要进行大量虚拟化。
有时我需要选择某一列中的一大堆(如果不是全部)单元格,以共同更改它们的值。对于任何感兴趣的人,我通过单击列标题(通常对列进行排序)并调用以下方法来实现这一点:
private void SelectColumn(object sender, DataGridSortingEventArgs e)
{
if (MyDataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
{
DataGridColumn column = e.Column;
if (e.Column != null)
{
MyDataGrid.UnselectAllCells();
for (int i = 0; i < MyDataGrid.Items.Count; i++)
{
MyDataGrid.SelectedCells.Add(new DataGridCellInfo(MyDataGrid.Items[i], column));
}
// Set the first cell into editing mode
MyDataGrid.CurrentCell = MyDataGrid.SelectedCells[0];
}
}
}
编辑:抱歉,我差点忘了添加设置选定单元格值的代码...:
private void MyDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (MyDataGrid.SelectedCells.Count > 1)
{ // More than 1 cell are selected
if (e.EditingElement.GetType() == typeof(TextBox))
{ // The cell being edited is of type TextBox
string value = ((TextBox)e.EditingElement).Text;
foreach (DataGridCellInfo cellInfo in MyDataGrid.SelectedCells)
{
DataGridCell gridCell = TryToFindGridCell(MyDataGrid, cellInfo);
if (gridCell != null) gridCell.Content = value; // ((TextBox)e.EditingElement).Text returns the Text in the cell sending DataGridCellEditEndingEventArgs e
}
}
}
}
static DataGridCell TryToFindGridCell(DataGrid grid, DataGridCellInfo cellInfo)
{
DataGridCell result = null;
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);
if (row != null)
{
int columnIndex = grid.Columns.IndexOf(cellInfo.Column);
if (columnIndex > -1)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
}
}
return result;
}
如果所有选定的单元格都在我的 GUI 的可见区域内,这将非常有效。 但是,由于外部的所有内容(有几行作为缓冲区)都被虚拟化,所以我遇到了问题。虚拟化的行并没有真正被选中,可见区域之外的任何单元格都不会与可见的单元格一起改变它们的值。
任何人都可以指导我找到更好的方法吗?是的,我需要处理这么多数据,抱歉。 ;)
【问题讨论】:
-
你again。 ;o)
-
对不起,哈哈。我认为现在关于 SO 上的 WPF DataGrid 的所有问题中有一半是我的。
-
我不了解虚拟化,但我很确定如果您知道列,您可以连续获取一个单元格。你不能用这种方式得到所有的细胞吗?
-
这可能不是最好的建议,但如果假设支持网格的数据是可观察的集合。获取编辑值并直接修改可观察集合可能是有意义的。
-
网格后面的数据是一个DataTable。
标签: c# wpf select datagrid virtualization