Sunday, July 6, 2014

Linear motion with XAML and Storyboard animations!

One of the remarkably cool things with XAML is how easy it is to set up animations.  Most of the time I just need to animate some opacity.  A quick web search, and boom!  I’m in business.
But for some reason, animating motion (like: move my text box off screen) is a pain.  Here are the important steps.
  1. Give your object an x:Name (“obj”).  Let’s also assume that the object is a custom object of type local:JokeControl.  The word local refers to a XML namespace definition.
  2. Add a RenderTransform with a TranslateTransform child to your object
  3. Add in a storyboard and give it an x:Naem
  4. Set the storyboard’s TargetName to the object name
  5. Set the storyboard’s TargetProperty using the weird ‘path’ syntax: (local:JokeControl.RenderTransform).(TranslateTransform.X)
And then in code, just call “.Begin()” on the animation!
Here are the actual bits of code:
From the XAML file:
Notes Code
Set up the ‘local’ namespace so that my user control (which is in C# namespace ‘Jokes’) can be used. xmlns:local="using:Jokes"
Create the animation in the resource section.  The storyboard (animation) is named uiAnimateJokeOut, and actually has more bits than this. <Grid.Resources>
    <Storyboard x:Name="uiAnimateJokeOut" >
        <DoubleAnimation
            Storyboard.TargetName="uiJokeControl"
            Storyboard.TargetProperty="(local:JokeControl.RenderTransform).(TranslateTransform.X)"
            From="0.0" To="400.0" Duration="0:0:0.5"
            AutoReverse="False"
                         />
The object I want to animate needs a RenderTransform; the particular render transform I need is a Translate transform.  I don’t have to name it because I’ll find it by type. <local:JokeControl x:Name="uiJokeControl" Grid.Column="1" >
    <local:JokeControl.RenderTransform>
        <TranslateTransform X="0" >
        </TranslateTransform>
    </local:JokeControl.RenderTransform>
</local:JokeControl>
C# code to start the animation uiAnimateJokeOut.Begin();
While I’m at it – I wanted the joke control to move right to go off screen, and then come back.  And I wanted to change the joke when it’s off the screen.  I did this by making two animations (one for joke OUT and one for joke IN).  I then added a .Completed on the OUT to swap jokes and to bring the joke back in.
The code looks like this:
uiAnimateJokeOut.Completed += (s, args) => { DoRandom(); uiAnimateJokeIn.Begin(); };