Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Fire event when DataGridCell is clicked

Tags:

c#

wpf

datagrid

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?

like image 836
user3428422 Avatar asked Dec 04 '22 06:12

user3428422


2 Answers

Use DataGridCellStyle and hook PreviewMouseDown event.

<DataGrid>
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <EventSetter Event="PreviewMouseDown" Handler="b1SetColor"/>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>
like image 195
Rohit Vats Avatar answered Dec 22 '22 04:12

Rohit Vats


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");
}
like image 30
PiotrWolkowski Avatar answered Dec 22 '22 04:12

PiotrWolkowski