单击DataGridCell时的WPF Fire事件

时间:2014-06-26 14:22:43

标签: c# wpf wpfdatagrid

我想在点击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("Clicked");
  }

但是当我点击Combobox单元格时,没有任何事情发生(没有发生)。有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:8)

使用 DataGridCellStyle 并摘取 PreviewMouseDown 事件。

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

答案 1 :(得分:2)

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

XAML:

<DataGrid SelectedCellsChanged="selectedCellsChanged"/>

C#:

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

答案 2 :(得分:1)

将此添加到网格

 SelectionUnit="Cell"

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