如何:使用焦点事件更改元素的颜色
更新:2007 年 11 月
本示例演示如何使用 GotFocus 和 LostFocus 事件在元素获取和失去焦点时更改元素的颜色。
本示例包括一个可扩展应用程序标记语言 (XAML) 文件和一个代码隐藏文件。有关完整示例,请参见当元素获取和失去焦点时激发事件的示例。
示例
下面的 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 获得键盘焦点时,Button 的 Background 会变为红色。 当 Button 失去键盘焦点时,Button 的 Background 会重新变为白色。
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;
}
}