The difference between GotFocus and GotKeyboardFocus The difference between GotFocus and GotKeyboardFocus wpf wpf

The difference between GotFocus and GotKeyboardFocus


MSDN has an overview of focus, but I'll try to explain it here.

WPF has 2 concepts regarding focus. There is the physical keyboard focus, and there is logical focus. Only one element can have keyboard focus (and if the application isn't the active application, no element will have keyboard focus).

Multiple items can have logical focus. In fact, you can create new "focus scopes". As per MSDN:

When keyboard focus leaves a focus scope, the focused element will lose keyboard focus but will retain logical focus. When keyboard focus returns to the focus scope, the focused element will obtain keyboard focus. This allows for keyboard focus to be changed between multiple focus scopes but ensures that the focused element in the focus scope regains keyboard focus when focus returns to the focus scope.

You can define your own focus scope on an element (typically a Panel) by setting FocusManager.IsFocusScope="True". The controls in WPF that are focus scopes by default are Window, MenuItem, ToolBar, and ContextMenu.

This makes sense if you think about having multiple Windows in your application. When you Alt-Tab between them, you expect your keyboard focus to return to the same place it was the last time the Window had focus. By keeping keyboard focus and logical focus separate, you can achieve this.