Reputation: 66320
Within a WPF datagrid's code behind, how do I get the currentCell from my dataGrid.SelectedItem (In Code)?
Many Thanks,
Upvotes: 5
Views: 12521
Reputation: 30097
Try this from post
You can retrieve row from dataGrid.SelectedIndex
and column by dataGrid.CurrentColumn.DisplayIndex
public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)
{
DataGridRow rowContainer = GetRow(dataGrid, row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
// now try to bring into view and retreive the cell
dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
Edit
public static DataGridRow GetRow(DataGrid dataGrid, int index)
{
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
dataGrid.ScrollIntoView(dataGrid.Items[index]);
dataGrid.UpdateLayout();
row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
you can find the complete source code here (look for code at end of page)
Upvotes: 8
Reputation: 3298
You can use CurrentCell.Item Property in the DataGrid itself:
DataGridCell cell = (DataGridCell)myDataGrid.CurrentCell.Item;
Upvotes: 0