wpfxamlmvvmkeypresskeyrelease

Handling Key press & release events in MVVM


I am developing a wpf application using MVVM pattern. I need to separately handle Key press & release events, (e.g. in media players fwd/rev happen till user keeps key pressed & stops when he releases). After searching a lot, still I couldn't find any way to do it. Can anybody please help.


Solution

  • Thanks for your suggestions. I found a way to do this by using interactivity triggers & dependency property. Following is the dependency property for 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);
            }
        }
    }
    

    Then just use it in the xaml as below:

        <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>
    

    Where the KeyReleaseCommand & KeyDownCommand are RelayCommand in your ViewModel.

        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");
                }
            }
        }