tags:

views:

1194

answers:

3

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.

+2  A: 

As per WPF documentation on MSDN:

In WPF there are two main concepts that pertain to focus: keyboard focus and logical focus. Keyboard focus refers to the element that receives keyboard input and logical focus refers to the element in a focus scope that has focus.

and

An element that has keyboard focus will also have logical focus, but an element that has logical focus does not necessarily have keyboard focus.

Tomalak
So it would be better to use Keyboard.Focus()? Strange, though, when I used item.Focus() the keyboard focus always had been on the item, too.
Sam
The others said pretty much the same thing as I did, just with code samples (yay!). Dunno why this was down voted...
Tomalak
I don't get the downvote, either. The difference between logical and keyboard focus is good info.
Joel B Fant
Community support FTW! :-D Thanks Joel.
Tomalak
A: 

Also, you may want to know that item.Focus() is the equivalent of calling:

DependencyObject focusScope = FocusManager.GetFocusScope(item);
if (FocusManager.GetFocusedElement(focusScope) == null)
{
   FocusManager.SetFocusedElement(focusScope, item);
}
decasteljau
+5  A: 

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);
}
Joel B Fant