从DataGrid中选择DataGridCell

gli*_*ite 10 .net c# wpf wpfdatagrid datagridcell

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

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

Phi*_*hil 5

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

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

dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(dataGridCellInfo);
dataGrid.CurrentCell = dataGridCellInfo;
Run Code Online (Sandbox Code Playgroud)

我看不到直接更新特定单元格内容的方法,因此为了更新特定单元格的内容,我将执行以下操作

// 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.
Run Code Online (Sandbox Code Playgroud)