如何:使用事件创建翻转效果
更新:2007 年 11 月
本示例演示如何在鼠标指针进入和离开元素所在的区域时更改元素的颜色。
本示例包括一个可扩展应用程序标记语言 (XAML) 文件和一个代码隐藏文件。有关完整示例,请参见鼠标指针示例。
说明: |
---|
示例
下面的 XAML 创建用户界面(它包括围绕在 TextBlock 周围的 Border),并将 MouseEnter 和 MouseLeave 事件处理程序附加到 Border 上。
<StackPanel>
<Border MouseEnter="OnMouseEnterHandler"
MouseLeave="OnMouseLeaveHandler"
Name="border1" Margin="10"
BorderThickness="1"
BorderBrush="Black"
VerticalAlignment="Center"
Width="300" Height="100">
<Label Margin="10" FontSize="14"
HorizontalAlignment="Center">Move Cursor Over Me</Label>
</Border>
</StackPanel>
下面的代码隐藏文件创建 MouseEnter 和 MouseLeave 事件处理程序。 当鼠标指针进入 Border 时,Border 的背景变成红色。 当鼠标指针离开 Border 后,Border 的背景又变回白色。
Partial Public Class Window1
Inherits Window
Public Sub New()
InitializeComponent()
End Sub
' raised when mouse cursor enters the are occupied by the element
Private Sub OnMouseEnterHandler(ByVal sender As Object, ByVal e As MouseEventArgs)
border1.Background = Brushes.Red
End Sub
' raised when mouse cursor leaves the are occupied by the element
Private Sub OnMouseLeaveHandler(ByVal sender As Object, ByVal e As MouseEventArgs)
border1.Background = Brushes.White
End Sub
End Class
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
// raised when mouse cursor enters the area occupied by the element
void OnMouseEnterHandler(object sender, MouseEventArgs e)
{
border1.Background = Brushes.Red;
}
// raised when mouse cursor leaves the area occupied by the element
void OnMouseLeaveHandler(object sender, MouseEventArgs e)
{
border1.Background = Brushes.White;
}
}