你用什么来填充你的数据网格?我通常使用我创建的这种方法从数据上下文而不是网格本身获取值。
private Tuple<string,int,string,int> SelectedCell(System.Windows.Controls.DataGrid dataGrid, int textIndex, int valueIndex)
{
string cellText = null, cellValue = null;
//if the text index is out of bounds, fix it
if (dataGrid.SelectedCells.Count < textIndex)
{
textIndex = dataGrid.SelectedCells.Count - 1;
}
else if (textIndex < 0)
{
textIndex = 0;
}
//if the value index is out of bounds, fix it
if (dataGrid.SelectedCells.Count < valueIndex)
{
valueIndex = dataGrid.SelectedCells.Count - 1;
}
else if (valueIndex < 0)
{
valueIndex = 0;
}
System.Data.DataRowView row = dataGrid.SelectedItem as System.Data.DataRowView;
if(row != null)
{
cellText = row[textIndex].ToString();
cellValue = row[valueIndex].ToString();
}
return new Tuple<string,int,string,int>(cellText,textIndex, cellValue, valueIndex);
}
它获取 2 个索引(列索引)的值,然后返回这些值以及这些值的索引,以防原始索引超出范围。