this works great. In my MainWindow.xaml file, I add two keyBinding commands to illustrate
<Window x:Class="MainWindowCommandBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.InputBindings> <KeyBinding Command="{Binding OpenCommand}" Gesture="Ctrl+O"/> <KeyBinding Command="{Binding CopyCommand}" Gesture="Ctrl+C"/> </Window.InputBindings> <Grid> </Grid> </Window>
In my MainWindow.xaml.cs file, I initialize my DataContext as follows.
public MainWindow() { InitializeComponent(); DataContext = new MainWindowContext(); }
The MainWindowContext class is defined as follows:
class MainWindowContext { RelayCommand _openCommand; public ICommand OpenCommand { get { if (_openCommand == null) { _openCommand = new RelayCommand( param => this.Open(), param => this.Open_CanExecute()); } return _openCommand; } set { _openCommand = (RelayCommand) value; } } RelayCommand _copyCommand; public ICommand CopyCommand { get { if (_copyCommand == null) { _copyCommand = new RelayCommand( param => this.Copy(), param => this.Copy_CanExecute()); } return _copyCommand; } set { _copyCommand = (RelayCommand)value; } } private bool Copy_CanExecute() { return true; } private object Copy() { Console.Out.WriteLine("Copy command executed"); return null; } private bool Open_CanExecute() { return true; } private object Open() { Console.Out.WriteLine("Open command executed"); return null; } }
When I execute, it works fine. You can see which command was executed in the console. Please tell me if I miss something.
source share