Fading Controls with Mouse Movement in WPF

This is an off-topic post from my IE Extension Writing (which I am working on, I promise!). I was playing with a WPF app;It’s a simple photo viewer. I wanted the UI to be “control-less” and only show the picture. However I also wanted some user interface elements to it as well. I decided to take the approach of using controls that will sit overtop of the image, and only fade them in when there is mouse movement, and then fade them out when the mouse is idle. Sort of like how Windows Media Player works when viewing a video in full screen.

It’s pretty quick, but it might save someone some time. This can be done easily and purely in XAML using Event Triggers. Here is the markup I used:

   1: <EventTrigger RoutedEvent="Mouse.MouseMove">


   2:     <BeginStoryboard HandoffBehavior="Compose">


   3:         <Storyboard AutoReverse="False">


   4:             <DoubleAnimation To="1" Storyboard.TargetName="ScaleSlider" Storyboard.TargetProperty="Opacity" Duration="0:0:0.1875" />


   5:             <DoubleAnimation To="0" Storyboard.TargetName="ScaleSlider" Storyboard.TargetProperty="Opacity" BeginTime="0:0:3.0" Duration="0:0:0.1875" />


   6:         </Storyboard>


   7:     </BeginStoryboard>


   8: </EventTrigger>

and this EventTrigger is on Window.Triggers. ScaleSlider is a slider control on the current window. You can use whatever control you’d like. When the mouse moves, it fades the control in, and fades it out after 3 seconds of the mouse being idle.

This is a quick and dirty app, but it should work for most people. The caveat to this simple example is all you are doing is hiding the control: users can still interact with it even though it isn’t visible, say through the keyboard. My work around for this is bind the IsEnabled of the control to it’s own Opacity. Here is the markup for my slider:

   1: <Slider Orientation="Vertical" Margin="0, 20, 30, 20" Maximum="5" Minimum="0.05" Value="1" TickFrequency="0.3"


   2:         Name="ScaleSlider" HorizontalAlignment="Right" Opacity="0" TickPlacement="BottomRight" ValueChanged="ScaleSlider_ValueChanged"


   3:         IsEnabled="{Binding Mode=OneWay, RelativeSource={x:Static RelativeSource.Self}, Path=Opacity}" />



This works nicely, it disables itself when the Opacity is zero.

One thought on “Fading Controls with Mouse Movement in WPF”

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>