0

The following code is working for usercontrols but not in the Mainwindows. Setting Focusable="True" for the mainwindow.

<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
    }
Geeth
  • 5,282
  • 21
  • 82
  • 133

1 Answers1

0

Got fixed by using the below code from the link. Keyboard shortcuts in WPF

public YourWindow() //inside any WPF Window constructor { ... //add this one statement to bind a new keyboard command shortcut InputBindings.Add(new KeyBinding( //add a new key-binding, and pass in your command object instance which contains the Execute method which WPF will execute new WindowCommand(this) { ExecuteDelegate = TogglePause //REPLACE TogglePause with your method delegate }, new KeyGesture(Key.P, ModifierKeys.Control))); ... } Create a simple WindowCommand class which takes an execution delegate to fire off any method set on it.

public class WindowCommand : ICommand { private 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();
    }
}

}

Geeth
  • 5,282
  • 21
  • 82
  • 133