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引用的, 然后在内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.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必须都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, IsKeyboardFocused则和IsKeyboardFocusWithintrue为。If calling Focus returns true, IsKeyboardFocused and IsKeyboardFocusWithin are also true.

如果还true没有相关属性, 则在调用Focus时, 将按以下顺序引发以下一个或多个事件: PreviewLostKeyboardFocusPreviewGotKeyboardFocus (源是新的焦点目标)、 IsKeyboardFocusedChangedIsKeyboardFocusWithinChangedLostKeyboardFocus ,GotKeyboardFocus (源为新的焦点目标)。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.

适用于