wpf UserControl InputBindings 仅在先按下按钮后才起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21347666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UserControl InputBindings Only working after pressing a button first
提问by Jim
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 buttonmanually the keybinds do workas intended. So obviously i would like to let the user use the keybind before any button press :)
问题:当第一次加载 UserControl 并且我没有按下其中的任何按钮时,Keybinds 不起作用。手动单击按钮后,键绑定按预期工作。所以显然我想让用户在按下任何按钮之前使用键绑定:)
(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)
我如何设置命令的示例代码:(使用 MVVM-light 工具包)
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;
}
回答by Rohit Vats
Like I mentioned in comment, control should have keyboard focus so that keyBindings can work on that control.
就像我在评论中提到的那样,控件应该具有键盘焦点,以便 keyBindings 可以在该控件上工作。
On button click it's working since with that click, userControl has got focus and hence bindings worked after that.
在单击按钮时,它开始工作,因为通过单击,userControl 获得了焦点,因此在此之后绑定工作。
On UserControl load, put keyboard focus on UserControl so that input bindings can work. You can put this code in UserControl constructor:
在 UserControl 加载时,将键盘焦点放在 UserControl 上,以便输入绑定可以工作。您可以将此代码放在 UserControl 构造函数中:
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):
这也可以通过 XAML 实现(关键是在 UserControl 上将 Focusable 设置为 True):
<Window FocusManager.FocusedElement="{Binding ElementName=userControl}">
<local:SampleUserControl x:Name="userControl" Focusable="True"/>
</Window>

