Jim Jim - 1 month ago 16
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)

ContextBinding


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


View


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


ViewModel


private RelayCommand _nextCommand;

/// <summary>
/// Gets the NextCommand.
/// </summary>
public RelayCommand NextCommand
{
get
{
return _nextCommand ?? (_nextCommand = new RelayCommand(
ExecuteNextCommand,
CanExecuteNextCommand));
}
}

private void ExecuteNextCommand()
{
SelectedGameImageIndex += 1;
}

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

Answer

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()
    {
        InitializeComponent();
        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"/>
</Window>