Create animations using XAML


IvorIvor Berry, Content Developer


Here’s a quick intro on creating simple animations in XAML, based off of the Hello World” app for C#/XAML, however this can be applied to any XAML app.

This example animates the opacity of two different objects in our app, but this method of animation can be used on any number of transforms. The nice thing is that you can nest all the DoubleAnimation definitions you want under a single Storyboard, and they will all happen when that Storyboard is invoked. Specifically, DoubleAnimation animates the specified property of the specified target. What properties can be animated depends on the target type, so check out the API definition for that target if you have any questions.

For reference, in this snippet I’ve hooked up the trigger of clicking the button to invoking the animation. If you look at the sample linked above, you’ll see the inputButton declared:


<Button x:Name="inputButton" Content="Say "Hello"" Click="Button_Click"/>

Notice the event handler at the end: Click=”Button_Click”. This is how we tell our app to go run that function in the code-behind file. When using this snippet, my function Button_Click looks like this:


private void Button_Click(object sender, RoutedEventArgs e)
{
 greetingOutput.Text = "Hello, " + nameInput.Text + "!";
 ButtonClicked.Begin();
}

The only thing I added was the ButtonClicked.Begin(). Now if you take a look at the animation snippet, which is the focus of this post, you’ll see I named the storyboard ButtonClicked. So, to invoke this animation, all I need to do is tell it to begin.


<StackPanel x:Name="contentPanel">
 <StackPanel.Resources>
  <Storyboard x:Name="ButtonClicked">
   <DoubleAnimation Storyboard.TargetName="greetingOutput"
    Storyboard.TargetProperty="Opacity"
    From="1"
    To="0"
    Duration="0:0:5"/>
   <DoubleAnimation Storyboard.TargetName="inputButton"
    Storyboard.TargetProperty="Opacity"
    To=".5"
    BeginTime="0:0:5"
    Duration="0:0:2"/>
   </Storyboard>
 </StackPanel.Resources>
...
<StackPanel>

When started in the code-behind, the greetingOutput textblock fades out, followed by the inputButton (the one labeled ‘Say “Hello”‘) dimming.

Now you have animations! Feel free to play with the timing, or animate different properties as you like.

Helpful links

Comments (0)

Skip to main content