Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between Keyboard.Focus(item) and item.Focus()?

Tags:

.net

wpf

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.

like image 840
Sam Avatar asked Oct 13 '08 09:10

Sam


People also ask

What is the 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.


1 Answers

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);
}
like image 163
Joel B Fant Avatar answered Oct 27 '22 01:10

Joel B Fant