在WPF中创建密钥绑定

dee*_*zen 23 c# wpf

我需要为Window创建输入绑定.

public class MainWindow : Window
{
    public MainWindow()
    {
        SomeCommand = ??? () => OnAction();
    }

    public ICommand SomeCommand { get; private set; }

    public void OnAction()
    {
        SomeControl.DoSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)
<Window>
    <Window.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="F5"></KeyBinding>
    </Window.InputBindings>
</Window>
Run Code Online (Sandbox Code Playgroud)

如果我使用一些CustomCommand初始化SomeCommand:ICommand它不会触发.从不调用SomeCommand属性get().

小智 56

对于你的情况最好的方式使用MVVM模式

XAML:

 <Window>
    <Window.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="F5"/>
    </Window.InputBindings>
 </Window>
 .....
Run Code Online (Sandbox Code Playgroud)

代码背后:

   public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
     }
Run Code Online (Sandbox Code Playgroud)

在您的视图模型中:

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

然后你需要一个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;
    }   
Run Code Online (Sandbox Code Playgroud)

  • 是否有任何快速简单的方法运行方法`void buttonPress(){MessageBox.Show("It works");`在任何特定的键组合上,例如Ctrl + A?我一直在谷歌搜索最近20分钟,我找不到一个简单的例子来做到这一点. (6认同)
  • @MKII 不要忘记将 `DataContext = this;` 添加到 `Mainwindow` 方法中 (2认同)

Pau*_*ole 14

对于修饰符(键组合):

<KeyBinding Command="{Binding SaveCommand}" Modifiers="Control" Key="S"/>
Run Code Online (Sandbox Code Playgroud)


Jit*_*oli 6

可能为时已晚,但这是最简单、最短的解决方案。

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" >
Run Code Online (Sandbox Code Playgroud)