I have a WPF screen that has half a dozen buttons. I'd like to associate each with a keybinding. They are all ICommand driven via MVVM.
I currently have the keybindings bound to the events and not the actual buttons:
<UserControl.InputBindings>
<KeyBinding Key="N" Command="{Binding MyCommand}"/>
However, for any Keybinding to work I have to set at least 1 button to focus in the codebehind. I'd really like to not do this because each button/command has different rules on if it's active or not and I have focus animation that I'd prefer wasn't active on page load.
Is this possible or do I have to set focus?
You just need to set usercontrol's focusable to true, because some element doesn't have it to true by default
<UserControl Focusable="True">
Then you have to set this.Focus() in the loaded event of the user control
It might be that you do need to focus on some element to get it to work, but perhaps you could just set focus on your entire UserControl without visual feedback? You could also try setting the focus to an invisible element if that does not work.
BTW, there seems to have been a similar question on here before: WPF MVVM KeyBinding not being recognized right away and not always working
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With