Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keybindings without any focus

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?

like image 596
itchi Avatar asked Nov 14 '11 22:11

itchi


2 Answers

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

like image 190
MaRuf Avatar answered Nov 13 '22 21:11

MaRuf


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

like image 21
Filip Skakun Avatar answered Nov 13 '22 23:11

Filip Skakun