Mapping command to key stroke globally in WPF

Below I have a small code sample that shows you how to map an ICommand to a specific keybinding and makes it available anywhere within the current WPF application. Below I have used an example of a save command that you would want to be callable from any window by pressing Ctrl+Shift+S.


    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            InputBinding saveInputCommand = new InputBinding(AppCommands.SaveCommand, new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control));
            this.InputBindings.Add(saveInputCommand);

            CommandBinding saveCommandBinding = new CommandBinding(AppCommands.SaveCommand);
            saveCommandBinding.Executed += this.Save;
            this.CommandBindings.Add(saveCommandBinding);
        }

        private void Save(object obSender, ExecutedRoutedEventArgs e)
        {
            //Save
        }
    }

    public class AppCommands
    {
        static AppCommands()
        {
            SaveCommand = new RoutedCommand(); //initialize this to the desired
        }

        public static ICommand SaveCommand { get; set; }
    }

Advertisements