如何识别我点击DataGrid
的位置?
<DataGrid x:Name="TheGrid" SelectionMode="Single" SelectionUnit="Cell" MouseDown="CellClick">
private void CellClick(object sender, MouseButtonEventArgs e)
{
foreach (DataGridCellInfo cell in TheGrid.SelectedCells)
{
MessageBox.Show(TheGrid.Items.IndexOf(cell.Item).ToString());
}
}
非常感谢
答案 0 :(得分:1)
您可以像这样处理SelectedCellsChanged
事件:
private void TheGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
if (TheGrid.SelectedCells.Count > 0)
{
DataGridCellInfo dgci = TheGrid.SelectedCells[0];
int columnIndex = dgci.Column.DisplayIndex;
DataGridRow row = TheGrid.ItemContainerGenerator.ContainerFromItem(dgci.Item) as DataGridRow;
int rowIndex = row.GetIndex();
MessageBox.Show($"Row {rowIndex} Column {columnIndex}");
}
}
答案 1 :(得分:0)
将在MouseUp上选择一个单元格。要在此事件发生之前获取单元格,您必须在Datagrid上侦听MouseDown并使用VisualTreeHelper.HitTest检查鼠标下的哪个元素。
结帐this回答。