In this post I’ll show you an easy way to add fade-in / fade-out effects to your user controls, when you change their
Adding the animation is done with an attached property, so using the code will be extremely simple.
Title="Window1" Height="300" Width="300">
<Button Content="Hide" Click="Hide_Click" />
<Button Content="Show" Click="Show_Click" />
Source="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg" />
private void Hide_Click(object sender, RoutedEventArgs e)
Image.Visibility = Visibility.Hidden;
private void Show_Click(object sender, RoutedEventArgs e)
Image.Visibility = Visibility.Visible;
Note that the only required addition for the animation effect was setting the attached property:
You can find here the full source code for the VisibilityAnimation attached property and here the usage sample application.
Where is the magic? The magic resides in the implementation of the attached property. Before I’ll show you the code, let me explain the basic idea.
- We “register” for getting visibility property “before change” event.
- When an element’s visibility property tries to change, somewhere in the application, we get the notification and check if the element has our attached property.
- If it has, we start an animation on the opacity property and force the current visibility value to
Visibility.Visible, This will allow the animation to present without interruptions.
- When the animation completes, we set the original requested value.
- Setting the original requested value will invoke (again) our “before change” event, so we need to keep a flag that indicates whether we already started the animation, in which case we just set the value.
Credit The original idea is based on an answer from stack overflow. I’ve improved the code, added support for the case where the Visibility was getting the value using data binding and added lots of comments.
That’s it for now,
Appendix A – Source Code for VisibilityAnimation Class