Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Key binding in WPF

Tags:

c#

wpf

xaml

I need to create input binding for Window.

public class MainWindow : Window {     public MainWindow()     {         SomeCommand = ??? () => OnAction();     }      public ICommand SomeCommand { get; private set; }      public void OnAction()     {         SomeControl.DoSomething();     } } 

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

If I init SomeCommand with some CustomCommand : ICommand it doesn't fire. SomeCommand property getter is never called.

like image 300
deeptowncitizen Avatar asked Oct 31 '13 01:10

deeptowncitizen


1 Answers

For your case best way used MVVM pattern

XAML:

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

Code behind:

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

In your view-model:

public class MyViewModel {     private ICommand someCommand;     public ICommand SomeCommand     {         get         {             return someCommand                  ?? (someCommand = new ActionCommand(() =>                 {                     MessageBox.Show("SomeCommand");                 }));         }     } } 

Then you'll need an implementation of ICommand. This simple helpful class.

public class ActionCommand : ICommand {     private readonly Action _action;      public ActionCommand(Action action)     {         _action = action;     }      public void Execute(object parameter)     {         _action();     }      public bool CanExecute(object parameter)     {         return true;     }      public event EventHandler CanExecuteChanged; }    
like image 55
Aleksey Avatar answered Oct 09 '22 03:10

Aleksey