共用方式為


Keyboard.GotKeyboardFocus 附加事件

定義

項目收到鍵盤焦點時發生。

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

範例

下列範例會TextBox建立 並附加 事件和 LostKeyboardFocus 事件的事件處理程式GotKeyboardFocusTextBox取得鍵盤焦點時,背景色彩會變更,並清除的TextBox文字。 TextBlock當 失去鍵盤焦點時,背景色彩會變更,而且會呼叫方法,以重設範例中使用的變數。

<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 語言概念,可參考未定義該事件的物件上可處理的 XAML 語言概念,WPF 也會藉由讓事件周遊路由來擴充該事件。 附加事件在程式代碼中沒有直接處理語法;若要在程式代碼中附加路由事件的處理程式,您可以使用指定的 Add*Handler 方法。 如需詳細資訊,請參閱 附加事件概觀

鍵盤焦點是指接收鍵盤輸入的物件。 具有鍵盤焦點的項目已 IsKeyboardFocused 設定為 true。 整個桌面上只能有一個鍵盤焦點的專案。 邏輯焦點是指焦點範圍內具有焦點的物件。 如需焦點、鍵盤焦點和邏輯焦點的詳細資訊,請參閱 輸入 概觀和 焦點概觀

PreviewGotKeyboardFocus如果已處理事件或PreviewLostKeyboardFocus事件,鍵盤焦點就會變更。

路由事件資訊

標識元欄位 GotKeyboardFocusEvent
路由策略 鼓 泡
代理人 KeyboardFocusChangedEventHandler

適用於