Logical focus refers to the FocusManager..::.FocusedElement in a focus scope. A focus scope is an element that keeps track of the FocusedElement within its scope. 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.
There can be multiple elements that have logical focus in an application, but there may only be one element that has logical focus in a particular focus scope.
An element that has keyboard focus has logical focus for the focus scope it belongs to.
An element can be turned into a focus scope in Extensible Application Markup Language (XAML) by setting the FocusManager attached property IsFocusScope to true. In code, an element can be turned into a focus scope by calling SetIsFocusScope.
The following example makes a StackPanel into a focus scope by setting the IsFocusScope attached property.
<StackPanel Name="focusScope1"
FocusManager.IsFocusScope="True"
Height="200" Width="200">
<Button Name="button1" Height="50" Width="50"/>
<Button Name="button2" Height="50" Width="50"/>
</StackPanel>
StackPanel focuseScope2 = new StackPanel();
FocusManager.SetIsFocusScope(focuseScope2, true);
GetFocusScope returns the focus scope for the specified element.
Classes in WPF which are focus scopes by default are Window, MenuItem, ToolBar, and ContextMenu.
GetFocusedElement gets the focused element for the specified focus scope. SetFocusedElement sets the focused element in the specified focus scope. SetFocusedElement is typically used to set the initial focused element.
The following example sets the focused element on a focus scope and gets the focused element of a focus scope.
// Sets the focused element in focusScope1
// focusScope1 is a StackPanel.
FocusManager.SetFocusedElement(focusScope1, button2);
// Gets the focused element for focusScope 1
IInputElement focusedElement = FocusManager.GetFocusedElement(focusScope1);