可重复使用的标签动画搞乱了堆栈布局

Reusable label animation messing up stack layout

private async void moveMessage()
    {
        movingLabel = new Label();
        movingLabel.HorizontalTextAlignment = TextAlignment.Center;
        stackLayoutContainingMovingText.Children.Add(movingLabel);

        Animation animation = new Animation();
        double height = Application.Current.MainPage.Height;
        movingLabel.Text = "MESSAGE";

        animation.Commit(movingLabel, "animation", 20, 0, Easing.Linear, (d, f) =>
        {
            movingLabel.TranslateTo(0, height, 0, Easing.Linear);
            movingLabel.TranslateTo(0, -height, 2000, Easing.Linear);
        });

        await Task.Delay(2000);

        stackLayoutContainingMovingText.Children.Remove(movingLabel);

    }

每次单击按钮时我都会调用此方法。 这将使文本标签从屏幕底部移动到顶部。

出于某种原因,我必须创建一个新标签并将其添加到 stacklayout 子项中,因为如果我不这样做,这个动画将只发生一次并且不会重复。

目前这种代码可以工作,但它会在动画期间将页面上的所有控件向上然后向下推。 我还希望能够多次按下按钮,这应该允许多个标签同时向上动画。

but it pushes all of the controls on the page up and then down during animation.

因为当你点击按钮时,标签是在按钮下创建的。这就是为什么页面上的所有控件都起来了。在动画之后,新标签被删除。所以页面向下。

在xaml中创建标签并使用代码制作上下

xaml:

 <StackLayout x:Name="stackLayoutContainingMovingText">

    <!--  Place new controls here  -->
    <Label
        x:Name="movingLabel"
        HorizontalOptions="Center"
        Text="Welcome to Xamarin.Forms!"
        VerticalOptions="EndAndExpand" />

    <Button
         HorizontalOptions="EndAndExpand"
        x:Name="btn_Move"
        Clicked="btn_Move_Clicked"
        Text="Move" />
</StackLayout>

后面的代码:

  private void btn_Move_Clicked(object sender, EventArgs e)
    {
        moveMessage();
    }

    private async void moveMessage()
    {  
        double up = Application.Current.MainPage.Height;
        double down = movingLabel.Height;

        await movingLabel.TranslateTo(0, -up, 2000, Easing.Linear);
        await movingLabel.TranslateTo(0, down, 2000, Easing.Linear);
    }

截图:

更新:

如果你想取消动画,你可以使用ViewExtensions.CancelAnimations

 ViewExtensions.CancelAnimations(movingLabel);

当你像下面这样把这个取消放在按钮点击时,它会停止当前的动画。

   private void btn_Cancel_Clicked(object sender, EventArgs e)
    {
        ViewExtensions.CancelAnimations(movingLabel);
    }

截图: