Click here to Skip to main content
15,867,686 members
Articles / Desktop Programming / WPF

Basic WPF Way to Implement and Include Animation in XAML

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
5 May 2014CPOL5 min read 28.7K   17  
This article will make an attempt to describe a basic way to start implementing animation in WPF.

Introduction

This article will make an attempt to describe a basic way to start implementing animation in WPF.

Background

Learning how to implement animation is not a must to be a C# WPF developer. However there are applications that are graphics intensive, for which animation is quite valuable. On the other hand, even for data-intensive UI application, which may not have much animation, however in few places putting animation may highlight criticality and directly focus on that partial user functionality. Placing animation in UI without usability in mind is not worth it, however using it appropriately which adds a particular value can enhance usability for user interface.

Implementing animation is simple and straight forward in XAML for WPF application. For beginners, it may seem complicated and may seem like large piece of work. But in reality, it is not complicated at all. In the article below, I'll attempt to make a few simple steps to get started to place simple animations in place using XAML. Once we know how to place animation in XAML code, there is not much more to it. After that more fancy and complex animation is fully contained inside the animation code (its' Storyboard) itself and plugin that piece of animation is still the same way simple as you would plug in a simple animation in your XAML code.

BeginStorybaord” is the tag in XAML to use to implement animation in WPF. If we just keep this in mind, we will have a happy animated XAML life!!

Using the Code

Exercise 1

  • Let us start with a simple TextBlock where we will display a line of error message as simple text in red color. (As you guessed, no animation yet)
  • Then we will implement a “Storyboard” inside BeginStoryboard to blink the text. (Implement using simple animation.)

Exercise 2

  • Create a simple Button with text as “Submit” (no animation).
  • Toggle background upon mouse enter (implement through animation).
  • Again, enhance this button with elliptical shape with some inner circles of different colors. (No animation yet)
  • Enhance further to plug in a “storyboard” to change color of a inner circle/ellipse of this button to toggle color upon mouse enter. (Implement with animation.)

Exercise 3

  • Take these story boards we created in line with controls (TextBlock in exercise 1 and Button in exercise 2) and place them within Windows.Resources section.
  • Use these story boards replacing the inline story boards you created in exercise 1 and 2.

Exercise 4 (Optional for learning how to plug in animation in XAML)

  • Additionally, we can now place these storyboards in a resource.xaml file and load as resource dictionary (this step is basic XAML and not particular to animation)
  • Create more complex animation using any tool such as Blend or Photoshop or Illustrator or any other graphics tools. (I'll leave this to you to use some graphics tool to create more complex storyboards)
  • Include this complex or a third party animation or an animation created by and handed over by some graphics designer group into resources file and include this in your WPF project and load as resource dictionary.
  • Use this storyboard pointing by the “key” as you have plugged in the simple animation in your BeginStoryboard tag.

Exercise 1

Let us create a simple TextBlock first.

XML
<TextBlock Foreground="Red" Text="Severe error, connection failed,

           please check log for more details"></TextBlock>

Now let us add animation so that the text of this TextBlock "blinks" when it is loaded by adding an event trigger. We'll add DoubleAnimation in its Storyboard for Loaded EventTrigger.

XML
<TextBlock.Triggers>
  <EventTrigger  RoutedEvent="Window.Loaded">

    <BeginStoryboard>
      <Storyboard>
               <DoubleAnimation Storyboard.TargetProperty="(TextBlock.Opacity)"

                From="1" To="0" AutoReverse="True"
                BeginTime="0:0:0" Duration="0:0:.125" RepeatBehavior="6x"
                                                 >

            </DoubleAnimation>
      </Storyboard>
    </BeginStoryboard>
  </EventTrigger>
</TextBlock.Triggers>

Exercise 2

Let us create a simple button.

XML
<Button Width="100" 
Height="30" Content="Submit"></Button>

Let us add an EventTrigger to perform animation during MouseEnter event. Let us add BeginStoryBoard and within it Storyboard to animate button background when mouse is over the button. And then when we run this and hover over the button, we will see that button background color is toggling twice from gray to dark green color.

XML
<Button Width="100" Height="30" Content="Submit">
            <Button.Background>
                <SolidColorBrush x:Name="innerCircleBrush" 
                Color="Gray"></SolidColorBrush>
           </Button.Background>

            <Button.Triggers>
                <EventTrigger RoutedEvent="Button.MouseEnter">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation Storyboard.TargetName="innerCircleBrush" 
                                Storyboard.TargetProperty="Color"
                                            From="Gray" 
                                            To="DarkGreen" AutoReverse="True"
                                           BeginTime="0:0:0" 
                                           Duration="0:0:.25" RepeatBehavior="2x"
                                            ></ColorAnimation>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            
</Button.Triggers>
        
</Button>

(Optional) Now, let us get a bit fancy and create a button and enhance by changing the Template of this button control to make it look "round" with few inner rings (circles/ellipses) of various color backgrounds. We will use a number of ellipses sitting on top of each other and then we will animate color of the inner most ellipse when mouse is over the button by implementing storyboard for ColorAnimation as its' MouseEnter event trigger.

XML
<Button Content="Submit">
            <Button.Template>
                <ControlTemplate>
                    <Grid>
                        <Ellipse Width="60" Height="60" Fill="SlateGray" 
                        VerticalAlignment="Center" HorizontalAlignment="Center"></Ellipse>
                        <Ellipse Width="55" Height="55" Fill="LightGray"  
                        VerticalAlignment="Center" HorizontalAlignment="Center"></Ellipse>
                        <Ellipse Width="45" Height="45" 
                        VerticalAlignment="Center" HorizontalAlignment="Center">
                            <Ellipse.Fill>
                                <SolidColorBrush x:Name="innerCircleBrush" Color="Gray"></SolidColorBrush>
                            </Ellipse.Fill>
                            <Ellipse.Triggers>
                                <EventTrigger RoutedEvent="Button.MouseEnter">
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <ColorAnimation Storyboard.TargetName="innerCircleBrush" 
                                        Storyboard.TargetProperty="Color"
                                            From="Gray" To="DarkGreen" AutoReverse="True"
                                            BeginTime="0:0:0" Duration="0:0:.25" RepeatBehavior="2x"
                                            ></ColorAnimation>
                                        </Storyboard>
                                    </BeginStoryboard>
                                </EventTrigger>
                            </Ellipse.Triggers>
                        </Ellipse>
                        <TextBlock Margin="2,0,0,2" Text="Submit" Foreground="White"  
                            VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>
                    </Grid>
                </ControlTemplate>
            </Button.Template>            
</Button>

In the above examples, we have created animation for event trigger. However, we can use animation for any types of triggers the same way.

Exercise 3

Once we create the Storyboard and plug them inline inside a trigger, we can move the Storyboard code into the resource section so that we can reuse for multiple controls where applicable. For example:

XML
<Window.Resources>
       <Storyboard x:Key="toggleColorStoryboard">
           <ColorAnimation Storyboard.TargetName="innerCircleBrush" Storyboard.TargetProperty="Color"
                                           From="Gray" To="DarkGreen" AutoReverse="True"
                                           BeginTime="0:0:0" Duration="0:0:.25" RepeatBehavior="2x"
                                           ></ColorAnimation>
       </Storyboard>
   </Window.Resources>

Then, we can reuse this storyboard as shown below either for the first basic button we created or the fancy round button we created.

XML
<BeginStoryboard Storyboard="{StaticResource toggleColorStoryboard}"/>

Exercise 4

Now we can move the Storyboard into a separate file in the project, let's say we call it Dictionary1.xaml. Content of this resource dictionary file will look like below after we move our Storyboard code in there.

XML
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Storyboard x:Key="toggleColorStoryboard">
        <ColorAnimation Storyboard.TargetName="innerCircleBrush" Storyboard.TargetProperty="Color"
                                            From="Gray" To="DarkGreen" AutoReverse="True"
                                            BeginTime="0:0:0" Duration="0:0:.25" RepeatBehavior="2x"
                                            ></ColorAnimation>
    </Storyboard>
</ResourceDictionary>

Once we do that, let us now include this resource dictionary into our main window xaml file as follows:

XML
<Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </Window.Resources>

The benefit of this is that we can include as many resource dictionary files as we want. We can place more complex storyboards that are created by third party or by various graphics tool or by some other group into a number of resource dictionary files. Then include them as Window.Resources and use them referring to them by the "Key" as shown in "Exercise 3" above.

Reference Material

More reading material below:

History

  • 5th May, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --