If you haven't looked at part 1 of this series, you might want to go back and check it out first. Also, all code here is based on VB.NET 2008 Express, to be certain that you can use totally free software.
In Part 1 of the tutorial, a first attempt at programming a way to make a Label component fade smoothly from nothing to full opacity was programmed using the old Windows Forms Timer component. In Part 6, we returned to the problem and used the System.Timers.Timer object ... mainly to illustrate how to perform multitasking in WPF. In this part of the tutorial, we finally use the objects designed for just this job in WPF, the Animation objects.
One of the first things to notice about WPF's animation is that you don't have to do any looping - as we have done in previous examples - to vary the opacity of the Label. WPF does it behind the scenes for us. In WPF, programming is generally "declarative" rather than "procedural". In other words, you "declare" what you want done and then allow the system to figure out how to do it. To appreciate the difference, check out the procedural code to animate the Label in Part 6 of the tutorial.
The first animation technique that will be used is the simplest, from a coding point of view, and doesn't use any special XAML. A standard Label and a Button to trigger the action is all we need:
Title="Window1" Height="343" Width="336" FontWeight="Bold">
*** About Visual Basic ***
The VB.NET code, however, has some new objects:
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs) _
Dim myDoubleAnimation As DoubleAnimation = _
.To = 0.0
.Duration = New Duration(TimeSpan.FromSeconds(5))
.AutoReverse = True
.RepeatBehavior = RepeatBehavior.Forever
System.Windows.Media.Animation (imported to make the code easier to read) provides the DoubleAnimation object. "Double" is part of the the name because only Double property values can be varied using this animation. (We'll see one that varies "Color" next.) This object takes the place of the Timer in previous examples. A rich set of properties and methods make this a very powerful object, but in this case, an internal timer is configured to vary the opacity from the base value of 1.0 to 0 and back again in 5 seconds.
Due to the unique requirements of animation, Opacity isn't the target of the animation. A Shared property of the WPF Label component called OpacityProperty is passed to the instance of DoubleAnimation in our project instead.
A more powerful way to animate is to use a Storyboard. This technique is shown on the next page - along with a download of the completed code.