Brian Gradin
Brian Gradin

Reputation: 2275

In what situations will WPF give keyboard focus back to the main window?

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.

Upvotes: 6

Views: 1563

Answers (1)

Daniel
Daniel

Reputation: 16439

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.

Upvotes: 3

Related Questions