0

I'm trying to create implicit show and hide animations for UIElements in code that can be dynamically added and removed from the visual tree. I've tried the following:

private void testButton_Tapped(object sender, TappedRoutedEventArgs e)
{
    var myImage = new Image();
    myImage.Source = new BitmapImage(new Uri("https://upload.wikimedia.org/wikipedia/commons/c/c4/PM5544_with_non-PAL_signals.png"));
    var visual = ElementCompositionPreview.GetElementVisual(myImage);
    var animation = visual.Compositor.CreateVector3KeyFrameAnimation();
    var easing = visual.Compositor.CreateLinearEasingFunction();
    animation.InsertKeyFrame(0f, new Vector3(1200f, 0f, 0f), easing);
    ElementCompositionPreview.SetImplicitShowAnimation(myImage, animation);
    TestGrid.Children.Add(myImage);
}

... and the app and debugger crash with an unhandled exception. Stepping through code the crash happens just as soon as I step past the closing brace of the method. Also note I've tried the same code but using all global variables so I don't think it's the GC.

Sean O'Neil
  • 1,222
  • 12
  • 22

1 Answers1

0

The problem is that you cannot get your visual in your code. Try change the location of the following code:

    TestGrid.Children.Add(myImage);

Put it right after your image definition. Then it will not crash. But the animation will not occur due to it's a implicit animation.

Barry Wang
  • 1,459
  • 1
  • 8
  • 12
  • Which would defeat the entire purpose. – Sean O'Neil Feb 19 '18 at 09:50
  • Setting an animation.Target property and an animation.Duration property has solved the crashing problem. The above code works when those two are set, however the initial Show animation does not take place until it's been removed and added again. Oddly this problem doesn't happen when animating Opacity. With Opacity it all works as expected. The Show animation takes place when first added provided the Visual.Opacity property is set to its desired starting value prior to adding it. – Sean O'Neil Feb 19 '18 at 09:50