单击DataGridCell时的WPF Fire事件

本文关键字:Fire 事件 WPF 时的 DataGridCell 单击 | 更新日期: 2023-09-27 18:10:27

我希望在单击WPF DataGrid中的单元格时触发一个事件,我已经尝试过

XAML

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

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

但是当我点击Combobox单元格时,什么也没有发生(不触发)。我有办法做到这一点吗?

单击DataGridCell时的WPF Fire事件

使用 DataGridCellStyle , PreviewMouseDown

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

DataGrid级别可以订阅SelectedCellsChanged事件:

XAML:

<DataGrid SelectedCellsChanged="selectedCellsChanged"/>
c#:

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

添加到网格

 SelectionUnit="Cell"

然后使用@PiotrWolkowski提供的selectedCellsChanged解决方案。更改SelectionUnit将使它触发,即使它是同一行