UIElement.Focus Method

Definition

Attempts to set focus to this element.

public:
 virtual bool Focus();
public bool Focus ();
abstract member Focus : unit -> bool
override this.Focus : unit -> bool
Public Function Focus () As Boolean

Returns

true if keyboard focus and logical focus were set to this element; false if only logical focus was set to this element, or if the call to this method did not force the focus to change.

Implements

Examples

The following example sets focus to a TextBox referenced by Name, and then adjusts the position of the cursor within the TextBox.

void OnClickMoveToStart(object sender, RoutedEventArgs e)
{
    tbPositionCursor.Focus();
    tbPositionCursor.Select(0, 0);
}
Private Sub OnClickMoveToStart(ByVal sender As Object, ByVal e As RoutedEventArgs)

    tbPositionCursor.Focus()
    tbPositionCursor.Select(0, 0)

End Sub

Remarks

To be focusable, Focusable and IsEnabled must both be true.

Even if the element is focusable and valid, the Focus preview events may be processed in a specific tree, and focus on that element may not be allowed (for example, in a composite control). In such a case, this method returns false.

In general, focus is controlled by two different concepts: keyboard focus and logical focus. These two concepts are not always the same. For more information, see Focus summary and Input Overview.

If calling Focus returns true, IsKeyboardFocused and IsKeyboardFocusWithin are also true.

If the related properties are not already true, when you call Focus, one or more of the following events are raised in the following order: PreviewLostKeyboardFocus, PreviewGotKeyboardFocus (source is the new focus target), IsKeyboardFocusedChanged, IsKeyboardFocusWithinChanged, LostKeyboardFocus, GotKeyboardFocus (source is the new focus target).

In order for this call to be successful, some other element in the application needed to have focus previously.

Applies to