次の使用例は、マウス ポインターが要素に入り、要素が占有する領域から離れる際に要素の色を変更する方法を示しています。
この例は、拡張アプリケーション マークアップ言語 (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 の背景が白に戻ります。
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
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET Desktop feedback