获取DataGrid中特定单元格的值
本文关键字:单元格 DataGrid 获取 | 更新日期: 2023-09-27 18:12:03
我有一个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列,那么我怎么找到它?
您可以尝试下面的代码,它将为您提供单元格。
if (selectedCellRow != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(selectedCellRow);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
var cellValue = cell.Content;
}