UIElement.Focus UIElement.Focus UIElement.Focus 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.



下列範例會將焦點設定為TextBox Name所參考的, 然後調整中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


要成為可設定Focusable焦點IsEnabled的, 而且true兩者都必須是。To 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). 在這種情況下, 這個方法false會傳回。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.

如果呼叫Focus true傳回, IsKeyboardFocusedIsKeyboardFocusWithin也是。trueIf calling Focus returns true, IsKeyboardFocused and IsKeyboardFocusWithin are also true.

如果沒有true相關的屬性, 當您呼叫Focus時, 會以下列順序引發下列一個或多個事件: PreviewLostKeyboardFocusPreviewGotKeyboardFocus (來源是新的焦點目標)、 IsKeyboardFocusedChangedIsKeyboardFocusWithinChangedLostKeyboardFocus ,GotKeyboardFocus (source 是新的焦點目標)。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.