此範例顯示如何在滑鼠指標進入和離開元素所佔用的區域時,變更元素的色彩。
這個範例包含 Extensible Application Markup Language (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 的背景會變更回白色。
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;
}
}
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