感谢您的建议。
我找到了一种通过使用交互触发器和依赖属性来做到这一点的方法。
以下是 Command 的依赖属性。
public class EventToCommand : TriggerAction<DependencyObject>
{
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Using a DependencyProperty as the backing store for Command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(EventToCommand), new PropertyMetadata(null));
protected override void Invoke(object parameter)
{
if (Command != null
&& Command.CanExecute(parameter))
{
Command.Execute(parameter);
}
}
}
然后在 xaml 中使用它,如下所示:
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyUp">
<ap:EventToCommand Command="{Binding KeyReleaseCommand}"></ap:EventToCommand>
</i:EventTrigger>
<i:EventTrigger EventName="KeyDown">
<ap:EventToCommand Command="{Binding KeyDownCommand}"></ap:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
其中 KeyReleaseCommand 和 KeyDownCommand 是 ViewModel 中的 RelayCommand。
public MainViewModel()
{
KeyDownCommand = new RelayCommand<KeyEventArgs>(OnKeyDown, null);
KeyReleaseCommand = new RelayCommand<KeyEventArgs>(OnKeyRelease, null);
}
private void OnKeyRelease(KeyEventArgs args)
{
if (args.KeyboardDevice.Modifiers == ModifierKeys.Alt)
{
if (args.SystemKey == Key.Left)
{
Trace.WriteLine("ALT+LEFT Released");
}
}
}
public void OnKeyDown(KeyEventArgs args)
{
if (args.IsRepeat)
return;
if (args.KeyboardDevice.Modifiers == ModifierKeys.Alt)
{
if(args.SystemKey == Key.Left)
{
Trace.WriteLine("ALT+LEFT");
}
}
}