在WPF数据网格的代码后台中,我怎样从我的dataGrid.SelectedItem(在代码中)获取当前单元格?
非常感谢!
从帖子中尝试以下方法:
您可以通过dataGrid.SelectedIndex
检索行,通过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;
}
编辑
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;
}
DataGridCell
还是 DataGridCellInfo
? - Haris HasanDataGridCell cell = (DataGridCell)myDataGrid.CurrentCell.Item;
.Item
。它指向的是你的 DataGridCell 内部的内容,而不是实际的 DataGridCell。 - Rachel