Keyboard.GotKeyboardFocus 附加事件

定义

在元素收到键盘焦点时发生。

see AddGotKeyboardFocusHandler, and RemoveGotKeyboardFocusHandler
see AddGotKeyboardFocusHandler, and RemoveGotKeyboardFocusHandler
see AddGotKeyboardFocusHandler, and RemoveGotKeyboardFocusHandler

示例

以下示例创建 并TextBox附加 事件和 LostKeyboardFocus 事件的事件处理程序GotKeyboardFocusTextBox当 获得键盘焦点时,背景色将更改并清除 的文本TextBoxTextBlock当 失去键盘焦点时,背景色将更改,并调用方法重置示例中使用的变量。

<Border BorderBrush="Black" BorderThickness="1"
        Width="200" Height="100" Margin="5">
  <StackPanel>
    <Label HorizontalAlignment="Center" Content="Type Text In This TextBox" />
    <TextBox Width="175"
             Height="50" 
             Margin="5"
             TextWrapping="Wrap"
             HorizontalAlignment="Center"
             VerticalScrollBarVisibility="Auto"
             GotKeyboardFocus="TextBoxGotKeyboardFocus"
             LostKeyboardFocus="TextBoxLostKeyboardFocus"
             KeyDown="SourceTextKeyDown"/>
  </StackPanel>
</Border>
private void TextBoxGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    TextBox source = e.Source as TextBox;

    if (source != null)
    {
        // Change the TextBox color when it obtains focus.
        source.Background = Brushes.LightBlue;

        // Clear the TextBox.
        source.Clear();
    }
}
Private Sub TextBoxGotKeyboardFocus(ByVal sender As Object, ByVal e As KeyboardFocusChangedEventArgs)
    Dim source As TextBox = TryCast(e.Source, TextBox)

    If source IsNot Nothing Then
        ' Change the TextBox color when it obtains focus.
        source.Background = Brushes.LightBlue

        ' Clear the TextBox.
        source.Clear()
    End If
End Sub
private void TextBoxLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    TextBox source = e.Source as TextBox;

    if (source != null)
    {
        // Change the TextBox color when it loses focus.
        source.Background = Brushes.White;

        // Set the  hit counter back to zero and updates the display.
        this.ResetCounter();
    }
}
Private Sub TextBoxLostKeyboardFocus(ByVal sender As Object, ByVal e As KeyboardFocusChangedEventArgs)
    Dim source As TextBox = TryCast(e.Source, TextBox)

    If source IsNot Nothing Then
        ' Change the TextBox color when it loses focus.
        source.Background = Brushes.White

        ' Set the  hit counter back to zero and updates the display.
        Me.ResetCounter()
    End If
End Sub

注解

这是一个附加事件。 WPF 将附加事件实现为路由事件。 附加事件本质上是一种 XAML 语言概念,用于引用可在未定义该事件的对象上处理的事件,WPF 通过允许事件遍历路由来扩展该事件。 附加事件在代码中没有直接处理语法;若要在代码中附加路由事件的处理程序,请使用指定的 Add*Handler 方法。 有关详细信息,请参阅 附加事件概述

键盘焦点是指接收键盘输入的对象。 具有键盘焦点的 元素已 IsKeyboardFocused 设置为 true。 整个桌面上只能有一个具有键盘焦点的元素。 逻辑焦点是指具有焦点的焦点范围内的对象。 有关焦点、键盘焦点和逻辑焦点的详细信息,请参阅 输入概述焦点概述

PreviewGotKeyboardFocus如果处理事件或PreviewLostKeyboardFocus事件,键盘焦点会更改。

路由事件信息

标识符字段 GotKeyboardFocusEvent
路由策略 鼓 泡
委托 KeyboardFocusChangedEventHandler

适用于