2

I am trying to bind an InputGesture to a Button. The XAML of my Button looks like this:

<Button x:Name="StopButton" Content="{Binding StopLabel}" Command="{Binding StopCommand}" IsEnabled="{Binding StartCommand.IsExecuting}" />

The StopCommand is instantiated in the ViewModel:

StopCommand = new Command(_someObject.btnStop_Click);

When I manually click the button, btnStop_Click() is executed as expected.

Now, I'd like to add an InputGesture (in the CodeBehind), in order to run btnStop_Click() if "Control + S" is clicked. My CodeBehind looks like this:

public MainControl()
{
    InitializeComponent();
    try
    {
        _cmd = new RoutedUICommand();
        _cmd.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
        CommandBindings.Add(new CommandBinding(_cmd, Interrupt_event_handler));
    }
    catch (Exception err)
    {
        MessageBox.Show(err.Message);
    }
}

private void Interrupt_event_handler(object sender, RoutedEventArgs e)
{
    if (StopButton.IsEnabled)
    {
        StopButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
    }
}

However, when I click "Control + S", nothing happens.

1 Answer 1

2

For me it looks like your binding your Gesture to the wrong control.

You need access to the InputBindings from your current Window.

Something like this:

var window = this.Parent as Window;    
window.InputBindings.Add(new InputBinding(yourStopButtonCommand, new KeyGesture(Key.S, ModifierKeys.Control)));

The technical Reason behind this is that InputBindings won't be executed for a control that isn't focused. A handler for the input binding is searched in the visual tree from the focused element to the visual tree's root (in our case the window). When a control is not focused, he won't be a part of that search path.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.