The Grayzone

Change Opacity of Border on MouseOver

The Problem

Recently I was looking for a way of changing the opacity of a Border control when the user mouse’s over it, and re-setting the opacity when the mouse leaves. I originally wanted to do it using VisualStateManagers but since there is no ControlTemplate this won’t work.

The Solution

The solution that I came up with (not necessarily the best but it works!) was to create a new class that inherits from the [Behavior](http://msdn.microsoft.com/en-us/library/ff726531%28v=Expression.40%29.aspx) class. I then define the opacity changes in this and it work’s a treat!

The Code

First I created a new class that inherits from Behavior. All I did was add a MouseEnter and MouseLeave event and change the opacity accordingly:

using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace TheGrayZone.Behaviours
{
  public class OpacityHoverBehaviour : Behavior<UIElement>
  {
    protected override void OnAttached()
    {
      base.OnAttached();

      this.AssociatedObject.MouseEnter += new MouseEventHandler(AssociatedObject_MouseEnter);
      this.AssociatedObject.MouseLeave += new MouseEventHandler(AssociatedObject_MouseLeave);
    }
  
    protected override void OnDetaching()
    {
      base.OnDetaching();

      this.AssociatedObject.MouseEnter -= new MouseEventHandler(AssociatedObject_MouseEnter);
      this.AssociatedObject.MouseLeave -= new MouseEventHandler(AssociatedObject_MouseLeave);
    }

    private void AssociatedObject_MouseLeave(object sender, MouseEventArgs e)
    {
      this.AssociatedObject.Opacity = 0.6;
    }

    private void AssociatedObject_MouseEnter(object sender, MouseEventArgs e)
    {
      this.AssociatedObject.Opacity = 0.8;
    }
  }
}

Then in the UserControl containing the Border element use the following XAML. You need to include the System.Windows.Interactivity namespace and the namespace where your behaviour was declared.

<UserControl
...
  xmlns:behaviour="clr-namespace:TheGrayZone.Behaviours"
  xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">

<Border Style="{StaticResource BorderStyle}">
  <TextBlock Foreground="White" Text="Some Text"/>

  <i:Interaction.Behaviors>
    <behaviour:OpacityHoverBehaviour/>
  </i:Interaction.Behaviors>
</Border>

Finally I’ve defined the following style referenced in the above xaml.

<Setter Property="CornerRadius" Value="5,5,5,5"/>
<Setter Property="Background" Value="Black"/>
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Opacity" Value="0.6"/>

Share this: