UIElement.Focus Method


尝试将焦点设定到此元素上。Attempts to set focus to this element.

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



如果键盘焦点和逻辑焦点同时设定到此元素上,则为 true;如果只有逻辑焦点设定到此元素上或此方法调用未强制更改焦点,则为 falsetrue 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.



下面的示例将焦点设置到 Name引用的 TextBox,然后在 TextBox内调整光标的位置。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.Select(0, 0);
Private Sub OnClickMoveToStart(ByVal sender As Object, ByVal e As RoutedEventArgs)

    tbPositionCursor.Select(0, 0)

End Sub


若要获得可设定焦点,必须同时 trueFocusableIsEnabledTo be focusable, Focusable and IsEnabled must both be true.

即使元素可设定焦点并且有效,Focus 预览事件也可以在特定树中进行处理,并且可能不允许焦点在该元素上(例如,在复合控件中)。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). 在这种情况下,此方法将返回 falseIn 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.

如果调用 Focus 返回 true,则 IsKeyboardFocusedIsKeyboardFocusWithintrueIf calling Focus returns true, IsKeyboardFocused and IsKeyboardFocusWithin are also true.

如果尚未 true相关属性,则在调用 Focus时,会按以下顺序引发以下一个或多个事件: "PreviewLostKeyboardFocus"、"PreviewGotKeyboardFocus" (源为新的焦点目标)、IsKeyboardFocusedChangedIsKeyboardFocusWithinChangedLostKeyboardFocusGotKeyboardFocus (源为新的焦点目标)。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