Nasıl yapılır: Odak Olaylarını Kullanarak Öğenin Rengini Değiştirme
Bu örnek, ve olaylarını kullanarak odak kazanırsa ve kaybettiğinde bir öğenin renginin nasıl değiştirileceğini gösterir GotFocusLostFocus .
Bu örnek, bir Extensible Application Markup Language (XAML) dosyasından ve arka plan kod dosyasından oluşur.
Örnek
Aşağıdaki XAML, iki nesneden oluşan Kullanıcı arabirimini oluşturur Button ve GotFocus nesnelerine ve olaylarına olay işleyicileri ekler LostFocusButton .
<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>
Aşağıdaki kod arkasında GotFocus ve LostFocus olay işleyicileri oluşturulur. ButtonKazanç klavyesi odaklandığında, öğesinin ' ı BackgroundButton Red olarak değişir. ButtonKlavye odağı kaybettiğinde, ' Background nin Button geri dönmesi beyaz olarak değişir.
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