UserControl InputBindings仅在首先按下按钮后才能工作

时间:2014-01-25 06:52:35

标签: c# wpf xaml mvvm mvvm-light

通过点击按钮,按钮工作正常。

问题:当第一次加载UserControl并且我没有按任何按钮时,Keybinds无法正常工作。 手动点击按钮后,键绑定可以正常工作。所以很明显我想让用户在按下任何按钮之前使用keybind:)

(我已经尝试将注意力集中在不同的元素上,例如按钮本身)

示例代码,我如何设置我的命令:(使用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"/>

视图模型

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

1 个答案:

答案 0 :(得分:16)

就像我在评论中提到的那样, 控件应该具有键盘焦点,以便keyBindings可以在该控件上运行

  

在按钮上单击它,因为该单击,userControl具有   得到了关注,因此绑定工作在那之后。

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

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

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

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