Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a DataGrid WPF control and I want to get a specific DataGridCell. I know the row and column indices. How can I do this?

I need the DataGridCell because I have to have access to its Content. So if I have (for example) a column of DataGridTextColum, my Content will be a TextBlock object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
230 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use code similar to this to select a cell:

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

dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(dataGridCellInfo);
dataGrid.CurrentCell = dataGridCellInfo;

I can't see a way to update the contents of a specific cell directly, so in order to update the content of a specific cell I would do the following

// 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...