Search code examples
c#uwpwindows-community-toolkit

How To Trigger Implicit Composition Animations


Following the only documentation I could find, I tried the following XAML:

<Image Name="testImage" Source="https://upload.wikimedia.org/wikipedia/commons/c/c4/PM5544_with_non-PAL_signals.png" Width="800">
    <animations:Implicit.Animations>
        <animations:ScalarAnimation Target="Translation.Y" ImplicitTarget="Offset" Duration="0:0:4"/>
        <animations:ScalerAnimation Target="Opacity" Duration="0:0:4" />
    </animations:Implicit.Animations>
</Image>

The following code works and the opacity animates and takes 4 seconds to fade:

private void myButton_Tapped(object sender, TappedRoutedEventArgs e)
{
    testImage.Opacity = 0.2;
}

But I can't figure out how to trigger a translate animation (or rotate or scale). I've tried this:

private void myButton_Tapped(object sender, TappedRoutedEventArgs e)
{
    var translate = new TranslateTransform();
    translate.Y = 400;
    testImage.RenderTransform = translate;
}

And also this hoping the implicit would override the duration but no luck:

private void myButton_Tapped(object sender, TappedRoutedEventArgs e)
{
    testImage.Offset(0, 400, 0).Start();
}

The changes are applied in these, but no 4 second animation.


Solution

  • The TranslateTransform is a RenderTransform and is not related to the Composition transform you want to achieve and the Offset implicit animation overrides the XAML setting.

    To make it work, you need to get hold of the ElementVisual and then change the Offset directly:

    private void myButton_Tapped( object sender, TappedRoutedEventArgs e )
    {
        var imageVisual = ElementCompositionPreview.GetElementVisual( testImage );
        imageVisual.Offset = new Vector3( 0, 400, 0 );
    }