Search code examples
c#wpfdatagrid

WPF Fire event when DataGridCell is clicked


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?


Solution

  • Use DataGridCellStyle and hook PreviewMouseDown event.

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