UserControl InputBindings仅在首先按下按钮后才能工作 [英] UserControl InputBindings Only working after pressing a button first

查看:98
本文介绍了UserControl InputBindings仅在首先按下按钮后才能工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击按钮可以正常工作.

Buttons working fine as expected by clicking them.

问题:首次加载UserControl时,我没有按任何按钮,因此键绑定无效. 点击按钮后,键绑定可以正常工作.所以很明显,我想让用户在按下任何按钮之前先使用keybind:)

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)

我如何设置命令的示例代码:(使用MVVM-light工具包)

ContextBinding

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

查看

<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;
}

就像我在评论中提到的那样,

推荐答案

控件应具有键盘焦点,以便keyBindings可以在该控件上工作

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

在按钮单击上它起作用,因为单击该按钮,userControl具有 成为焦点,因此绑定工作在那之后.

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

在加载UserControl时,将键盘重点放在UserControl上,以便输入绑定可以正常工作.您可以将此代码放在UserControl构造函数中:

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);
    }


也可以通过XAML实现(关键是在UserControl上将Focusable设置为True)


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>

这篇关于UserControl InputBindings仅在首先按下按钮后才能工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆