【问题标题】:Handling Key press & release events in MVVM处理 MVVM 中的按键和释放事件
【发布时间】:2017-05-06 00:03:03
【问题描述】:

我正在使用 MVVM 模式开发一个 wpf 应用程序。我需要单独处理按键和释放事件(例如,在媒体播放器中 fwd/rev 发生,直到用户按住按键并在他释放时停止)。 在搜索了很多之后,我仍然找不到任何方法来做到这一点。有人可以帮忙吗?

【问题讨论】:

标签: wpf xaml mvvm keypress keyrelease


【解决方案1】:

感谢您的建议。 我找到了一种通过使用交互触发器和依赖属性来做到这一点的方法。 以下是 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");
            }
        }
    }

【讨论】:

    【解决方案2】:

    我猜,你会将Command 绑定到Button。如果您希望命令重复触发,您可以使用RepeatButton。它就是为此目的而设计的。您可以将您的命令绑定到Command 属性。它会重复触发你的方法,直到RepeatButton 被释放。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多