最好的方法是使用Items属性并直接访问您的数据项:
var dataItem = dataGrid.Items[0] as …;
当然也可以直接通过数据源进行获取,应为datagrid绑定数据之后是同步的,但是如果一个数据源还没有数据,需要从前台输入的时候,这是后光标还在单元格里面,就需要使用下面这种方法了,可以获取行列,然后根据行列来获取,用于插入批次等情况,方便操作
但是您可以使用此类来获取单元格并使用GetValue()方法访问该值(更像您的示例).
代码取自此处:datagrid get cell index
private void dgv_PreviewKeyDown(object sender,KeyEventArgs e)
{
if(e.Key==Key.Enter||e.Key==Key.Return)
{
int row=dgv.Items.IndexOf(dgv.CurrentItem);
int col=dgv.Columns.IndexOf(dgv.currentColumn);
//下面这个是获取单元格值的方法
string CellValue=DataGridHelper.GetCell(dgv,row,col).split(":")[1];
}
}
static class DataGridHelper {
static public DataGridCell GetCell(DataGrid dg,int row,int column) {
DataGridRow rowContainer = GetRow(dg,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
dg.ScrollIntoView(rowContainer,dg.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
static public DataGridRow GetRow(DataGrid dg,int index) {
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null) {
// may be virtualized,bring into view and try again
dg.ScrollIntoView(dg.Items[index]);
row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
static T GetVisualChild<T>(Visual parent) where T : Visual {
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++) {
Visual v = (Visual)VisualTreeHelper.GetChild(parent,i);
child = v as T;
if (child == null) {
child = GetVisualChild<T>(v);
}
if (child != null) {
break;
}
}
return child;
}
}