0

how can I recognize where I click on 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());
    }
}

many thanks

mm8
  • 163,881
  • 10
  • 57
  • 88
beari7
  • 105
  • 2
  • 15
  • Sorry, I dont understand how? – beari7 Apr 03 '18 at 18:25
  • I edit my Question. But this only work on >MouseUP< on MouseDown I get the "last" Cell... That's not the clean solution I'd like. is it possible to have a trigger that passes the line? – beari7 Apr 04 '18 at 05:42

2 Answers2

1

You could handle the SelectedCellsChanged event like this:

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}");

    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
0

A cell will get selected on MouseUp. To get the cell before this event occurred, you will have to listen on MouseDown on the Datagrid and check which element is under the mouse with VisualTreeHelper.HitTest.
Checkout this answer.

91378246
  • 367
  • 2
  • 5
  • 21