berti
berti

Reputation: 127

Click a WPF button programmatically

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.

Upvotes: 2

Views: 1352

Answers (1)

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.

Upvotes: 2

Related Questions