4
votes

I am looking to fire an event when a cell in a WPF DataGrid is clicked, I have tried

XAML

   <DataGridComboBoxColumn.ElementStyle>
      <Style TargetType="ComboBox">
         <EventSetter Event="GotFocus" Handler="b1SetColor"/>
      </Style>
   </DataGridComboBoxColumn.ElementStyle>

C#

  void b1SetColor(object sender, RoutedEventArgs e)
  {
     MessageBox.Show("Focused");
  }

But nothing happens (doesn't fire) when I do click the Combobox cell. is there a way I can achieve this?

3

3 Answers

12
votes

Use DataGridCellStyle and hook PreviewMouseDown event.

<DataGrid>
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <EventSetter Event="PreviewMouseDown" Handler="b1SetColor"/>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>
3
votes

On the level of DataGrid you can subscribe to SelectedCellsChanged event:

XAML:

<DataGrid SelectedCellsChanged="selectedCellsChanged"/>

C#:

void selectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    MessageBox.Show("Clicked");
}
1
votes

Add this to the grid

 SelectionUnit="Cell"

Then use the selectedCellsChanged solution provided by @PiotrWolkowski. Changing the SelectionUnit will make it fire even if it's the same row.