VD26
VD26

Reputation: 138

How to create and apply Spring Animation to a UWP control?

I intend to add a horizontal displacement with oscillating effect on a grid (LoginBody) upon loaded. After researching I think Spring Animation is the right thing to use. The code I derived from MS's tutorial so far is obviously not valid. For starter I'm not familiar with adding a CompositionObject into the visual tree. Also I'm not sure how to set "Offset.X" as the target property. Any advice would be appreciated.

  private void LoginBody_Loaded(object sender, RoutedEventArgs e)
    {
        Compositor _compositor = new Compositor();
        SpringScalarNaturalMotionAnimation _springAnimation =_compositor.CreateSpringScalarAnimation();
        _springAnimation.DampingRatio = 0.75f;
        _springAnimation.Period = TimeSpan.FromSeconds(0.5);
        _springAnimation.InitialValueExpressions["FinalValue"] = "this.StartingValue + 250";

        LoginBody.StartAnimation(_springAnimation);
    }

Upvotes: 1

Views: 186

Answers (1)

Sean O'Neil
Sean O'Neil

Reputation: 1241

You don't instantiate a new Compositor, it's a global object you simply want to reference. The easiest way:

Compositor _compositor = Window.Current.Compositor;

You don't mention what 'LoginBody' is or where it came from. If it is a UIElement that has been added to a XAML file, then it is already part of the Visual Tree. Or, if 'LoginBody' is type Visual that you obtained by using:

Visual LoginBody = ElementCompositionPreview.GetElementChildVisual(myUIElement);

That too is already part of the Visual Tree (assuming myUIElement is). However if 'LoginBody' is a newly created SpriteVisual or ContainerVisual, for example, then you have to add it to the Visual Tree like so:

ElementCompositionPreview.SetElementChildVisual(myGrid, LoginBody);

My guess is that just fixing your Compositor reference will put you on the right path.

Upvotes: 1

Related Questions