wpf datagrid enter键无法触发keydown
时间: 2023-12-16 08:04:43 浏览: 150
在WPF中,DataGrid控件的Enter键默认是用来完成单元格编辑的,因此无法触发KeyDown事件。如果想要在按下Enter键时触发KeyDown事件,可以通过以下两种方法实现:
1.在DataGridTextColumn的EditingElementStyle中添加PreviewKeyDown事件,将PreviewKeyDown事件转换为KeyDown事件,如下所示:
```xml
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}">
<EventSetter Event="PreviewKeyDown" Handler="DataGridTextColumn_PreviewKeyDown"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
```
在代码中实现DataGridTextColumn_PreviewKeyDown方法:
```csharp
private void DataGridTextColumn_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
e.Handled = true;
var textBox = sender as TextBox;
var eventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Enter);
eventArgs.RoutedEvent = UIElement.KeyDownEvent;
textBox.RaiseEvent(eventArgs);
}
}
```
2.在DataGrid的PreviewKeyDown事件中,判断当前按下的键是否为Enter键,如果是,则将PreviewKeyDown事件转换为KeyDown事件,如下所示:
```csharp
private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
e.Handled = true;
var eventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Enter);
eventArgs.RoutedEvent = UIElement.KeyDownEvent;
(sender as DataGrid).RaiseEvent(eventArgs);
}
}
```
阅读全文