C# 单击DataGridCell时WPF激发事件

C# 单击DataGridCell时WPF激发事件,c#,wpf,datagrid,C#,Wpf,Datagrid,我希望在单击WPF数据网格中的单元格时触发一个事件,我已经尝试过了 XAML 但是,当我单击组合框单元格时,不会发生任何事情(不会触发)。有什么方法可以实现这一点吗?在DataGrid级别,您可以订阅SelectedCellsChanged事件: XAML: 使用DataGridCellStyle并钩住PreviewMouseDown事件 <DataGrid> <DataGrid.CellStyle> <Style TargetType="D

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

XAML


但是,当我单击组合框单元格时,不会发生任何事情(不会触发)。有什么方法可以实现这一点吗?

DataGrid
级别,您可以订阅
SelectedCellsChanged
事件:

XAML:


使用DataGridCellStyle并钩住PreviewMouseDown事件

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

将其添加到网格中

 SelectionUnit="Cell"

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

我相信只有在不同行中选择单元格时才会激发。如果用户在同一行中选择不同的单元格(即不同的列),则不会命中该单元格。如果我错了,请更正。即使所选单元格与上一个所选单元格位于同一行,它也会触发。NirmaIL是正确的。只有在单击其他行时才会激发。如何在不破坏单元格中其余(继承的)样式的情况下激发?@RobertHarvey,您可以创建一个
Style
,并使用
BasedOn
以另一个样式为基础。
<DataGrid SelectedCellsChanged="selectedCellsChanged"/>
void selectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    MessageBox.Show("Clicked");
}
<DataGrid>
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <EventSetter Event="PreviewMouseDown" Handler="b1SetColor"/>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>
 SelectionUnit="Cell"