如何:使用焦点事件更改元素的颜色

此示例演示如何在元素使用 GotFocusLostFocus 事件获取和失去焦点时更改元素的颜色。

此示例包含 Extensible Application Markup Language (XAML) 文件和代码隐藏文件。

示例

以下 XAML 创建用户界面,该用户界面包含两个 Button 对象,并将 GotFocusLostFocus 事件的事件处理程序附加到 Button 对象。

<StackPanel>
  <StackPanel.Resources>
    <Style TargetType="{x:Type Button}">
      <Setter Property="Height" Value="20"/>
      <Setter Property="Width" Value="250"/>
      <Setter Property="HorizontalAlignment" Value="Left"/>
    </Style>
  </StackPanel.Resources>
  <Button
      GotFocus="OnGotFocusHandler"
      LostFocus="OnLostFocusHandler">Click Or Tab To Give Keyboard Focus</Button>
  <Button
      GotFocus="OnGotFocusHandler"
      LostFocus="OnLostFocusHandler">Click Or Tab To Give Keyborad Focus</Button>
</StackPanel>

下面的代码隐藏文件创建 GotFocusLostFocus 事件处理程序。 当 Button 获得键盘焦点时,ButtonBackground 变为红色。 当 Button 失去键盘焦点时,ButtonBackground 变回白色。

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    // Raised when Button gains focus.
    // Changes the color of the Button to Red.
    private void OnGotFocusHandler(object sender, RoutedEventArgs e)
    {
        Button tb = e.Source as Button;
        tb.Background = Brushes.Red;
    }
    // Raised when Button losses focus.
    // Changes the color of the Button back to white.
    private void OnLostFocusHandler(object sender, RoutedEventArgs e)
    {
        Button tb = e.Source as Button;
        tb.Background = Brushes.White;
    }
}
Partial Public Class Window1
    Inherits Window

    Public Sub New()
        InitializeComponent()
    End Sub

    'raised when Button gains focus. Changes the color of the Button to red.
    Private Sub OnGotFocusHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim tb As Button = CType(e.Source, Button)
        tb.Background = Brushes.Red
    End Sub

    'raised when Button loses focus. Changes the color back to white.
    Private Sub OnLostFocusHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim tb As Button = CType(e.Source, Button)
        tb.Background = Brushes.White
    End Sub
End Class

另请参阅