In a WPF application I'm working on, I have a MenuItem
with two items in it. When the MenuItem
is clicked, it takes keyboard focus and opens its submenu. When the MenuItem
is clicked again, the submenu is closed and for some reason, the main window takes keyboard focus. I need the MenuItem
to keep focus.
I have been told that in certain other situations, the main window may be given keyboard focus - for instance, if a control has keyboard focus and IsEnabled
or IsVisible
becomes false
. In which situations does this happen? I've been Googling like crazy but haven't found any information about this.
When an HTML element is able to handle keyboard input, it is said to have focus. Exactly one element is able to have focus in a time. In most browsers, users can move focus by pressing the Tab key and the Shift + Tab keys.
Keyboard focus refers to the element that is currently receiving keyboard input. There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true .
As far as I can tell, this is the expected behavior. WPF Menus are focus scopes by default, so any control within the menu that receives focus won't change the main logical focus of the window.
Also, certain WPF controls will sometimes call Keyboard.Focus(null);
(e.g. Button
does this when clicked). This call has the effect of returning the keyboard focus to the main logical focus. I suspect this is also happening when a menu is closed.
Try disabling the focus scope on the menu: <Menu FocusManager.IsFocusScope="False">
When the menu item receives the keyboard focus, and it's not in any focus scope, it will gets the main logical focus. This means the Keyboard.Focus(null)
call will keep the focus on the menu item. Jowever, this will also prevent commands in the submenu from returning the focus to the non-menu window content, so routed commands won't be able to find their target.
See "For What was FocusScope Designed?" in Using the WPF FocusScope.
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