#777 – Animating a Transform

You can animate any of the 2D transforms applied to an element by using a Storyboard that contains an object that derives from AnimationTimeline.

In the example below, we use two DoubleAnimation objects to animate the X and properties of a TranslateTransform, so that the TextBlock wanders around the screen.

For the X property of the transform, we specify that we want it to vary from -100 to 100 and then back again, taking 0.7 seconds and then repeating the pattern forever.  We do something similar for Y, but using a different time period.

    <Grid>
        <TextBlock Text="We shall overcome" HorizontalAlignment="Center" VerticalAlignment="Center"
                   Padding="20,10" Background="PaleGoldenrod" FontSize="16">
            <TextBlock.RenderTransform>
                <TranslateTransform x:Name="transTransform" X="-100" Y="-80"/>
            </TextBlock.RenderTransform>
            <TextBlock.Triggers>
                <EventTrigger RoutedEvent="TextBlock.Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetName="transTransform"
                                             Storyboard.TargetProperty="X"
                                             From="-100" To="100" Duration="0:0:0.7"
                                             AutoReverse="True" RepeatBehavior="Forever"/>
                            <DoubleAnimation Storyboard.TargetName="transTransform"
                                             Storyboard.TargetProperty="Y"
                                             From="-80" To="80" Duration="0:0:1.5"
                                             AutoReverse="True" RepeatBehavior="Forever"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </TextBlock.Triggers>
        </TextBlock>
    </Grid>

777-001
777-002