我有一个 WPF 控件 DataGrid
,我想要获取一个特定的 DataGridCell
。我知道它的行和列索引,那么我该如何做呢?
我需要获取这个 DataGridCell
是因为我要访问它的内容。所以如果我有(例如)一个 DataGridTextColumn
列,我的内容将是一个 TextBlock
对象。
我有一个 WPF 控件 DataGrid
,我想要获取一个特定的 DataGridCell
。我知道它的行和列索引,那么我该如何做呢?
我需要获取这个 DataGridCell
是因为我要访问它的内容。所以如果我有(例如)一个 DataGridTextColumn
列,我的内容将是一个 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.
DataGridCell
而不是DataGridCellInfo
,因为我需要访问DataGridCell
内容。我尝试了这个方法,但GetVisualChild
方法返回一个空子对象,因此无法工作。 - gliderkitepublic 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<DataGridCellsPresenter>(row);
if (presenter == null)
{
grid.ScrollIntoView(row, grid.Columns[column]);
presenter = GetVisualChild<DataGridCellsPresenter>(row);
}
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
return cell;
}
return null;
}
grid.ScrollIntoView
是在 DataGrid 虚拟化且所需单元格当前不在视图中时使其工作的关键。
详细信息请查看此链接 - 获取 WPF DataGrid 行和单元格
/// <summary>
/// Get the cell of the datagrid.
/// </summary>
/// <param name="dataGrid">The data grid in question</param>
/// <param name="cellInfo">The cell information for a row of that datagrid</param>
/// <param name="cellIndex">The row index of the cell to find. </param>
/// <returns>The cell or null</returns>
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<DataGridCellsPresenter>(row);
if (presenter != null)
{
result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
}
else
{
result = null;
}
}
}
}
return result;
}`
FindVisualChild
方法的实现在哪里? - NathanAldenSr