Подтвердить что ты не робот

Создать привязку клавиш в WPF

Мне нужно создать привязку ввода для окна.

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>

Если я запустил SomeCommand с некоторым CustomCommand: ICommand, он не срабатывает. Свойство someCommand get() никогда не вызывается.

4b9b3361

Ответ 1

Для вашего случая наилучшим образом использован шаблон MVVM

XAML:

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

Код позади:

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

В вашей модели вида:

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

Тогда вам понадобится реализация ICommand. Этот простой полезный класс.

 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;
    }   

Ответ 2

Для модификаторов (комбинаций клавиш):

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

Ответ 3

Вам нужно будет создать собственный Command интерфейс ICommand и инициализировать SomeCommand с помощью экземпляра Command.

Теперь вы должны установить DataContext окна для себя, чтобы сделать работу Command Binding:

public MainWindow()
{
    InitializeComponents();
    DataContext = this;
    SomeCommand = MyCommand() => OnAction();
}

ИЛИ вам нужно будет обновить свой Binding как

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

Ответ 4

Это может быть слишком поздно, но вот самое простое и самое короткое решение.

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.S)
    {
         // Call your method here
    }
}

<Window x:Class="Test.MainWindow" KeyDown="Window_KeyDown" >