UIElement.Focus UIElement.Focus UIElement.Focus UIElement.Focus Method

定義

嘗試將焦點設定至此項目。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

傳回

如果邏輯與鍵盤焦點設定至此項目,則為 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.

實作

範例

下列範例會將焦點設TextBox所參考Name,然後調整游標的位置內TextBoxThe 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

備註

若要可設定焦點,FocusableIsEnabled兩者都必須是trueTo 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會傳回trueIsKeyboardFocusedIsKeyboardFocusWithin還有trueIf calling Focus returns true, IsKeyboardFocused and IsKeyboardFocusWithin are also true.

如果相關的屬性尚未存在true,當您呼叫Focus,以下列順序引發一或多個下列事件: PreviewLostKeyboardFocusPreviewGotKeyboardFocus (來源為新的焦點目標), 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.

適用於