Bagikan melalui


Cara: Mengubah Warna Elemen Menggunakan Peristiwa Fokus

Contoh ini menunjukkan cara mengubah warna elemen saat mendapatkan dan kehilangan fokus dengan menggunakan peristiwa GotFocus dan LostFocus.

Contoh ini terdiri dari file Extensible Application Markup Language (XAML) dan file code-behind.

Contoh

XAML berikut membuat antarmuka pengguna, yang terdiri dari dua objek Button, dan melampirkan penanganan aktivitas untuk peristiwa GotFocus dan LostFocus ke objek 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>

Kode berikut di belakang membuat penanganan aktivitas GotFocus dan LostFocus. Saat Button mendapatkan fokus keyboard, Background dari Button diubah menjadi merah. Ketika Button hilang fokus dari keyboard, Background dari Button diubah kembali menjadi putih.

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

Lihat juga