Condividi tramite


How to: Create a Rollover Effect Using Events

This example shows how to change the color of an element as the mouse pointer enters and leaves the area occupied by the element.

This example consists of a Extensible Application Markup Language (XAML) file and a code-behind file. For the complete samples, see Mouse Pointer Sample.

NoteNote:

This example demonstrates how to use events, but the recommended way to achieve this same effect is to use a Trigger in a style. For more information, see Styling and Templating.

Example

The following XAML creates the user interface, which consists of Border around a TextBlock, and attaches the MouseEnter and MouseLeave event handlers to the 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>

The following code behind creates the MouseEnter and MouseLeave event handlers. When the mouse pointer enters the Border, the background of the Border is changed to red. When the mouse pointer leaves the Border, the background of the Border is changed back to white.

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
    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
    Sub OnMouseLeaveHandler(ByVal sender As Object, ByVal e As MouseEventArgs)
        border1.Background = Brushes.White
    End Sub
End Class