It can be very helpful to create shortkey in your application. How we can do it in a WPF MVVM application? From the .NET Framework 4, it is easy. Let’s see it and how it works!

In your xaml, write these lines:

    <Window.InputBindings>
        <KeyBinding Key="F5" Command="{Binding refreshAll}"/>
    </Window.InputBindings>

In this way, when user will press the key “F5”, the command “refreshAll” will be executed.

Here the definition of my refreshAll, to give to you an example of a command definition:

        private ICommand p_refreshAll;
        public ICommand refreshAll
        {
            get
            {
                if (p_refreshAll == null)
                {
                    p_refreshAll = new DelegateCommand(delegate()
                    {
                        setNotifier();
                        updateDataClick();
                    });
                }
                return p_refreshAll;
            }
        }

Further, if you want, for example, binding a save function when user press “Ctrl+S”, you can write this xaml:

<KeyBinding Command="{Binding SaveCommand}" Modifiers="Control" Key="S"/>

And if you want to binding a triple-key-pression? For example, to save with Ctrl+Shift+S, you can write this:

<KeyBinding Command="{Binding SaveCommand}" Modifiers="Control+Shift" Key="S"/>
Advertisements