通过点击按钮,按钮可以正常工作。
问题:当第一次加载 UserControl 并且我没有按其中的任何按钮时,键绑定(bind)不起作用。 手动点击按钮后,键绑定(bind)会正常工作。所以很明显我想让用户在按下任何按钮之前使用键绑定(bind):)
(我已经尝试将焦点设置在不同的元素上,例如按钮本身)
我如何设置命令的示例代码:(使用 MVVM-light 工具包)
上下文绑定(bind)
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"/>
View 模型
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 可以在该控件上工作。
On button click it's working since with that click, userControl has got focus and hence bindings worked after that.
加载 UserControl 时,将键盘焦点放在 UserControl 上,以便输入绑定(bind)可以工作。您可以将此代码放在 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>
关于c# - UserControl InputBindings 仅在先按下按钮后工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21347666/