方法 : イベントを使用してロールオーバー効果を作成する

この例では、ある要素が占める領域にマウス ポインターが出入りするのに合わせて、要素の色を変更する方法を示します。

この例は、Extensible Application Markup Language (XAML) ファイルと分離コード ファイルで構成されています。

メモメモ

この例ではイベントを使用する方法を示しますが、これと同じ効果を実現するには、スタイルで Trigger を使用する方法が推奨されます。詳細については、「スタイルとテンプレート」を参照してください。

使用例

次の XAML は、Border で囲まれた TextBlock で構成されるユーザー インターフェイスを作成し、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;
    }
}