Jim Jim - 1 year ago 140
C# Question

UserControl InputBindings Only working after pressing a button first

Buttons working fine as expected by clicking them.

Issue: When the UserControl is loaded for the first time and i didn't press any button in it, the Keybinds are not working. After clicking a button manually the keybinds do work as intended. So obviously i would like to let the user use the keybind before any button press :)

(I already tried to set focus on different elements such as the button itself)

Sample code, of how i setup my commands: (using MVVM-light toolkit)


DataContext="{Binding GameInfoViewModel, Source={StaticResource Locator}}"


<KeyBinding Key="Right" Command="{Binding NextCommand}"/>
<mui:ModernButton Name="ModernButtonNext" IconData="{StaticResource NextIcon}" Command="{Binding NextCommand}" Margin="16 0 0 0" EllipseDiameter="24" IconWidth="14" IconHeight="14" ToolTip="Next image"/>


private RelayCommand _nextCommand;

/// <summary>
/// Gets the NextCommand.
/// </summary>
public RelayCommand NextCommand
return _nextCommand ?? (_nextCommand = new RelayCommand(

private void ExecuteNextCommand()
SelectedGameImageIndex += 1;

private bool CanExecuteNextCommand()
if (SelectedGameImageIndex >= GameImages.Count - 1)
return false;
return true;

Answer Source

Like I mentioned in comment, control should have keyboard focus so that keyBindings can work on that control.

On button click it's working since with that click, userControl has got focus and hence bindings worked after that.

On UserControl load, put keyboard focus on UserControl so that input bindings can work. You can put this code in UserControl constructor:

    public SampleUserControl()
        Focusable = true;
        Loaded += (s, e) => Keyboard.Focus(this);

Also that can be achieved via XAML too (key thing is to set Focusable to True on UserControl):

<Window FocusManager.FocusedElement="{Binding ElementName=userControl}">
   <local:SampleUserControl x:Name="userControl" Focusable="True"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download