In WPF, there are two ways to set the focus to an element.
You can either call the .Focus() method of the input element, or call Keyboard.Focus() with the input element as parameter.
// first way:
item.Focus();
// alternate way:
Keyboard.Focus(item);
What is the difference between these two? Are there special reasons to use one of them instead of the other in some cases?
So far I noticed no difference - what ever method I used, the item always got logical focus as well as keyboard focus.
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.
One of the first things that item.Focus()
does is call Keyboard.Focus( this )
. If that fails, then it makes calls to FocusManager
, as decasteljau has answered.
The following are copied from disassambler view in Reflector.
This is from UIElement
(UIElement3D
is the same):
public bool Focus()
{
if (Keyboard.Focus(this) == this)
{
return true;
}
if (this.Focusable && this.IsEnabled)
{
DependencyObject focusScope = FocusManager.GetFocusScope(this);
if (FocusManager.GetFocusedElement(focusScope) == null)
{
FocusManager.SetFocusedElement(focusScope, this);
}
}
return false;
}
This is from ContentElement
:
public bool Focus()
{
return (Keyboard.Focus(this) == this);
}
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