我有一个DataGrid。现在我想要从特定单元格中获取数据以进行比较。为此我找到了那个单元格的rowindex。我想要第二列的数据。到目前为止,我在datagrid的KeyDown事件中的代码如下所示:
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
if (dep is DataGridCell)
{
//cancel if datagrid in edit mode
maindg.CancelEdit();
//Check if selected cell is on second column and last row
if (maindg.CurrentColumn.DisplayIndex == 1)
{
DependencyObject depObj = dep;
//Find Row to which selectedCell belongs
while ((depObj != null) && !(depObj is DataGridRow))
{
depObj = VisualTreeHelper.GetParent(depObj);
}
DataGridRow selectedCellRow = depObj as DataGridRow;
if (FindRowIndex(selectedCellRow) == maindg.Items.Count - 1)
{
if (Here I want to check if cell's value is null or empty)
{
btnSave.Focus();
return;
}
}
}
}
我在谷歌搜索过这个问题。但无论在哪里,我都能获得所选细胞的价值。假设我想找到属于第5行和第4列的单元格的值,那我该如何找到呢?
答案 0 :(得分:3)
您可以尝试下面的代码,它会为您提供单元格。
if (selectedCellRow != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(selectedCellRow);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
var cellValue = cell.Content;
}