FrameworkElement.OnGotFocus(RoutedEventArgs) 方法


每当未处理的 GotFocus 事件在其路由中到达此元素时调用。Invoked whenever an unhandled GotFocus event reaches this element in its route.

 override void OnGotFocus(System::Windows::RoutedEventArgs ^ e);
protected override void OnGotFocus (System.Windows.RoutedEventArgs e);
override this.OnGotFocus : System.Windows.RoutedEventArgs -> unit
Protected Overrides Sub OnGotFocus (e As RoutedEventArgs)



包含事件数据的 RoutedEventArgsThe RoutedEventArgs that contains the event data.


与基元素公开的其他 On * 方法不同,OnGotFocus 具有默认实现。Unlike some other On* methods exposed by the base elements, OnGotFocus does have a default implementation. 具体而言,它具有一个实现,该实现替代下一级基本元素中的 null 实现,OnGotFocusSpecifically, it has an implementation that overrides the null implementation in the next level of base element down, OnGotFocus. 调用时,如果由于键盘焦点导致事件源自当前元素,则 OnGotFocus 在此元素上设置相应的焦点行为。When invoked, OnGotFocus sets appropriate focus behavior on this element in cases where the event originated from the current element due to keyboard focus. 即使将焦点设置为当前元素,OnGotFocus 处理程序也不会将事件参数标记为已处理。The OnGotFocus handler does not mark the event arguments as handled, even when focus is set to the current element. 如果事件的源是树中的另一个元素(而不是当前元素),则处理程序不执行任何操作。If the event's source was another element in the tree (not the current element), the handler does nothing.

您可以重写此方法以更改元素上的默认焦点行为,但是请注意,通过这种方式更改焦点行为可能会更好,因为根本不允许元素获得焦点(请参阅 Focusable)。You can override this method in order to change the default focus behavior on your element, but be aware that changing focus behavior in this way might be better accomplished by not allowing the element to be focusable at all (see Focusable).


如果打算在参数中将事件标记为已处理,则应注意元素树中其他父元素中事件处理的结果。If you intend to mark the event handled in the arguments, you should be aware of consequences on event handling in other parent elements in the element tree. 由于此处理程序使用冒泡路由处理事件,因此,根据事件参数将焦点设置为当前 sender 可能不合适。Because this handler acts on an event with a bubbling routing, setting the focus to the current sender per the event arguments may not be appropriate. 焦点可能需要转到复合子元素或父元素,具体取决于特定控件的组合。Focus might need to go to either a composite child element or to a parent element, depending on the compositing of certain controls. 因此,仅建议将焦点事件标记为 "已处理",前提是该事件要路由到的整个可视化树都是您创作的控件组合的一部分。Therefore marking a focus event as handled is only recommended if the entirety of the visual tree that the event is routing through is part of compositing of a control that you authored.