Partilhar via


Como: Change the Color of an Element Using Focus Events

Este exemplo mostra como modificar a cor de um elemento quando ele recebe e perde foco utilizando os eventos GotFocus e LostFocus.

Esse exemplo consiste em um arquivo Extensible Application Markup Language (XAML) e um arquivo code-behind. Para os exemplos completos, veja Acionar eventos quando um elemento obtém e perde o foco exemplo.

Exemplo

O XAML a seguir cria a interface de usuário, que consiste de dois objetos Button e anexa manipuladores de eventos para os eventos GotFocus e LostFocus aos objetos 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>

O código a seguir cria os manipuladores de eventos GotFocus e LostFocus. Quando o Button ganha o foco de teclado, o Background do Button muda para vermelho. Quando o Button perde o foco de teclado, o Background do Button muda de volta para branco.

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
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;
    }
}

Consulte também

Tarefas

Manipular o foco por programação exemplo

Conceitos

Input Overview