How to set a property without using an animation (Composition Api)?

119 views Asked by At

Question, how can we set a value for a property on Visual without using an animation? For example this works for me (for a Translation) but I feel there must be a better way. I'm using an animation of 1 millisecond to set a value immediately:

ElementCompositionPreview.SetIsTranslationEnabled(MyRectangle, true);

var visual = ElementCompositionPreview.GetElementVisual(MyRectangle);
var anim = compositor.CreateScalarKeyFrameAnimation();

anim.InsertKeyFrame(1.0f, 100f);
anim.Duration = TimeSpan.FromMilliseconds(1);

visual.StartAnimation("Translation.Y", anim);
2

There are 2 answers

4
Barry Wang On BEST ANSWER

The document has already said translation is not on visual: These properties have the same purpose and behavior as the like-named properties on the composition Visual class (except for Translation, which isn't on Visual).


Edit:

First of all, thanks Maximus for sharing:

ElementCompositionPreview.SetIsTranslationEnabled(MyRectangle, true);

I'm still not quite sure about your specific problem right now. But for the question of the title: "How to set a property without using an animation", do you mean something like this:

ElementCompositionPreview.SetIsTranslationEnabled(MyRectangle, true);
  var myInteropVisualPropertySet = ElementCompositionPreview.GetElementVisual(MyRectangle).Properties;
  myInteropVisualPropertySet.InsertVector3("Translation", new Vector3(0f,100f,0f));

In addition, I have the following code example for the "Suppose and were to-to-be Offset as you stated, is and a-to-set it directly with animation" question:

private void MyRectangle_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var compositor = Window.Current.Compositor;
            Visual visual = ElementCompositionPreview.GetElementVisual(MyRectangle);
            var vertical = compositor.CreateVector3KeyFrameAnimation();
            vertical.InsertKeyFrame(1.0f, new Vector3(0f, 100f, 0f));
            vertical.Duration = TimeSpan.FromMilliseconds(1);
            visual.StartAnimation("Offset", vertical);
        }

By the way, if you are just focus on animate a UI element(not visual), community toolkit contains a easy function for offset

0
Maximus On

Here is an example of what I did based on @Barry Wang's answer:

var props = ElementCompositionPreview.GetElementVisual(MyRectangle).Properties;

if (props.TryGetVector3("Translation", out var vect) == CompositionGetValueStatus.Succeeded)
{
    props.InsertVector3("Translation", new Vector3(vect.X, 150f, vect.Z));
}