UserControl InputBindings Only works after clicking a button first

The buttons work fine, as expected by clicking on them.

Problem: When UserControl boots for the first time, and I did not press a single button in it, Keybinds do not work. After manually clicking the button, keybinds work as intended. Therefore, obviously, I would like to allow the user to use keybind before pressing any button :)

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

Sample code on how to configure my commands: (using the 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;
}
+4
source share
1

, , keyBindings .

, , userControl , , , .

UserControl UserControl, . UserControl:

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

XAML ( - Focusable True UserControl):

<Window FocusManager.FocusedElement="{Binding ElementName=userControl}">
   <local:SampleUserControl x:Name="userControl" Focusable="True"/>
</Window>
+13

Source: https://habr.com/ru/post/1523663/


All Articles