另外不得不提一下我的解决方案。我有一个父视图,它处理来自所有子视图模型的 keyDown 事件。我为 DatePicker、MaskedTextBox 等特殊控件声明了一种行为,这些控件捕获 previewKeyDown 隧道事件并引发 KeyDown 冒泡事件:
public class EnterPressedBehavior : Behavior<UIElement>
{
public ICommand EnterPressedCommand { get; private set; }
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PreviewKeyDown += EnterPressed;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PreviewKeyDown -= EnterPressed;
}
private void EnterPressed(object sender, KeyEventArgs keyEventArgs)
{
if (Keyboard.PrimaryDevice != null && Keyboard.PrimaryDevice.ActiveSource != null)
{
var eventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, keyEventArgs.Key) { RoutedEvent = UIElement.KeyDownEvent };
AssociatedObject.RaiseEvent(eventArgs);
}
}
}
分配给 datePicker 的这种行为:
<DatePicker x:Name="BirthDateDatePicker" Grid.Column="1"
Grid.Row="6" Margin="3" HorizontalAlignment="Stretch"
IsEnabled="{Binding PersonFieldsEditDenied}"
Validation.ErrorTemplate="{StaticResource DefaultValidationTemplate}"
AutomationProperties.AutomationId="BirthDateDatePicker">
<i:Interaction.Behaviors>
<viewModels:EnterPressedBehavior />
</i:Interaction.Behaviors>
</DatePicker>
由父视图监听:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title=""
KeyDown="OnKeyDownHandler">
后面的代码:
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// your code
}
}