Практическое руководство. Изменение цвета элемента с помощью событий фокуса
Обновлен: Ноябрь 2007
В этом примере демонстрируется изменение цвета элемента при получении и потере фокуса с помощью событий GotFocus и LostFocus.
Этот пример состоит из файла Язык XAML (Extensible Application Markup Language) и файла кода программной части Полные примеры см. в разделе Пример возникновения событий при получении и потере фокуса элементом.
Пример
Следующий XAML создает интерфейс пользователя, состоящий из двух объектов Button, и связывает обработчики событий GotFocus и LostFocus с объектами 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>
Следующий код программной части создает обработчики событий GotFocus и LostFocus. Когда Button получает фокус ввода с клавиатуры, Background элемента Button изменяется на красный. Когда Button теряет фокус ввода с клавиатуры, Background элемента Button изменяется обратно на белый.
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;
}
}
См. также
Задачи
Пример программного управления фокусом