单击 DataGridCell 时的 WPF Fire 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24433065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:00:48  来源:igfitidea点击:

WPF Fire event when DataGridCell is clicked

c#wpfwpfdatagrid

提问by user3428422

I am looking to fire an event when a cell in a WPF DataGrid is clicked, I have tried

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

XAML

XAML

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

C#

C#

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

But nothing happens (doesn't fire) when I do click the Combobox cell. is there a way I can achieve this?

但是当我单击 Combobox 单元格时,没有任何反应(不会触发)。有没有办法实现这一目标?

回答by Rohit Vats

Use DataGridCellStyleand hook PreviewMouseDownevent.

使用DataGridCellStyle和钩子PreviewMouseDown事件。

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

回答by PiotrWolkowski

On the level of DataGridyou can subscribe to SelectedCellsChangedevent:

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

XAML:

XAML:

<DataGrid SelectedCellsChanged="selectedCellsChanged"/>

C#:

C#:

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