从DataGrid中选择DataGridCell

我有一个DataGrid WPF控件,我想获得一个特定的DataGridCell 。 我知道行和列索引。 我怎样才能做到这一点?

我需要DataGridCell因为我必须能够访问其内容。 因此,如果我(例如)有一个DataGridTextColum列,我的Content将是一个TextBlock对象。

您可以使用与此类似的代码来选择单元格:

 var dataGridCellInfo = new DataGridCellInfo( dataGrid.Items[rowNo], dataGrid.Columns[colNo]); dataGrid.SelectedCells.Clear(); dataGrid.SelectedCells.Add(dataGridCellInfo); dataGrid.CurrentCell = dataGridCellInfo; 

我看不到直接更新特定单元格内容的方法,所以为了更新特定单元格的内容,我会做以下几点

 // gets the data item bound to the row that contains the current cell // and casts to your data type. var item = dataGrid.CurrentItem as MyDataItem; if(item != null){ // update the property on your item associated with column 'n' item.MyProperty = "new value"; } // assuming your data item implements INotifyPropertyChanged the cell will be updated. 

你可以简单地使用这种扩展方法 –

 public static DataGridRow GetSelectedRow(this DataGrid grid) { return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem); } 

并且您可以通过现有的行和列ID获取DataGrid的单元格:

 public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column) { if (row != null) { DataGridCellsPresenter presenter = GetVisualChild(row); if (presenter == null) { grid.ScrollIntoView(row, grid.Columns[column]); presenter = GetVisualChild(row); } DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); return cell; } return null; } 

grid.ScrollIntoView是使DataGrid虚拟化并且当前不在视图中所需单元格的关键。

检查此链接以获取详细信息 – 获取WPF DataGrid行和单元格

这是我使用的代码:

  ///  /// Get the cell of the datagrid. ///  /// The data grid in question /// The cell information for a row of that datagrid /// The row index of the cell to find.  /// The cell or null private DataGridCell TryToFindGridCell(DataGrid dataGrid, DataGridCellInfo cellInfo, int cellIndex = -1) { DataGridRow row; DataGridCell result = null; if (dataGrid != null && cellInfo != null) { if (cellIndex < 0) { row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item); } else { row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(cellIndex); } if (row != null) { int columnIndex = dataGrid.Columns.IndexOf(cellInfo.Column); if (columnIndex > -1) { DataGridCellsPresenter presenter = this.FindVisualChild(row); if (presenter != null) { result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell; } else { result = null; } } } } return result; }` 

这假设已经加载了DataGrid(执行了自己的Loaded处理程序)。