c# - Crear enlace de clave en WPF
(2)
Para modificadores (combinaciones de teclas):
<KeyBinding Command="{Binding SaveCommand}" Modifiers="Control" Key="S"/>
Necesito crear un enlace de entrada para la ventana.
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>
Si inicio SomeCommand con algún CustomCommand: ICommand no se dispara. La propiedad SomeCommand get () nunca se llama.
Para su caso la mejor manera de utilizar el patrón MVVM.
XAML:
<Window>
<Window.InputBindings>
<KeyBinding Command="{Binding SomeCommand}" Key="F5"/>
</Window.InputBindings>
</Window>
.....
Código detrás:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
En su modelo de vista:
public class MyViewModel
{
private ICommand someCommand;
public ICommand SomeCommand
{
get
{
return someCommand
?? (someCommand = new ActionCommand(() =>
{
MessageBox.Show("SomeCommand");
}));
}
}
}
Entonces necesitarás una implementación de ICommand. Esta clase simple y útil.
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;
}