WPF窗口中未触发快捷方式

时间:2018-02-06 09:45:14

标签: wpf keyboard-shortcuts

以下代码适用于usercontrols,但不适用于Mainwindows。设置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
    }

1 个答案:

答案 0 :(得分:0)

使用链接中的以下代码修复了问题。 Keyboard shortcuts in WPF

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

public class WindowCommand:ICommand {     私人MainWindow _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();
    }
}

}