How to: Change the Color of an Element Using Focus Events
This example shows how to change the color of an element when it gains and loses focus by using the GotFocus and LostFocus events.
This example consists of a Extensible Application Markup Language (XAML) file and a code-behind file.
Example
The following XAML creates the user interface, which consists of two Button objects, and attaches event handlers for the GotFocus and LostFocus events to the Button objects.
<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>
The following code behind creates the GotFocus and LostFocus event handlers. When the Button gains keyboard focus, the Background of the Button is changed to red. When the Button loses keyboard focus, the Background of the Button is changed back to 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
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;
}
}