快捷方式未在 WPF 中触发 window

Shortcut is not triggering in WPF window

以下代码适用于用户控件,但不适用于主窗口。为主窗口设置 Focusable="True"。

<Window.InputBindings>
  <KeyBinding Modifiers="Ctrl" Key="S" Command="{Binding SaveCommand}" />
</Window.InputBindings>

    private ICommand _saveCommand;
    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new RelayCommand(
                    param => this.SaveObject(),
                    param => this.CanSave()
                );
            }
            return _saveCommand;
        }
    }

    private bool CanSave()
    {
        return (Project != null);
    }

    private void SaveObject()
    {
        // Code here
    }

已使用 link 中的以下代码修复。 Keyboard shortcuts in WPF

public YourWindow() //在任何 WPF Window 构造函数中 { ... //添加这个语句来绑定一个新的键盘命令快捷键 InputBindings.Add(new KeyBinding( //添加一个新的键绑定,并传入包含 WPF 将执行的 Execute 方法的命令对象实例 新 Window 命令(这个) { ExecuteDelegate = TogglePause //用你的方法委托替换 TogglePause }, new KeyGesture(Key.P, ModifierKeys.Control))); ... } 创建一个简单的 WindowCommand class,它需要一个执行委托来触发其上设置的任何方法。

public class Window命令:ICommand { 私人主要Window _window;

//Set this delegate when you initialize a new object. This is the method the command will execute. You can also change this delegate type if you need to.
public Action ExecuteDelegate { get; set; }

//You don't have to add a parameter that takes a constructor. I've just added one in case I need access to the window directly.
public WindowCommand(MainWindow window)
{
    _window = window;
}

//always called before executing the command, mine just always returns true
public bool CanExecute(object parameter)
{
    return true; //mine always returns true, yours can use a new CanExecute delegate, or add custom logic to this method instead.
}

public event EventHandler CanExecuteChanged; //i'm not using this, but it's required by the interface

//the important method that executes the actual command logic
public void Execute(object parameter)
{
    if (ExecuteDelegate != null)
    {
        ExecuteDelegate();
    }
    else
    {
        throw new InvalidOperationException();
    }
}

}