UWP故事板无法正确执行动画

时间:2019-03-20 22:49:36

标签: c# uwp

我有一个小按钮,应该在垂直和水平方向上进行调整。我想使用Storyboard并在转换下操纵X和Y。

我想在代码后边做

按钮移动到正确的位置,但是没有动画处于活动状态。

private void AnimatePlayerMovement(Player player)
{
    //This will hold hour animation
    Piece.RenderTransform = new CompositeTransform();

    //New storyboard
    Storyboard storyboard = new Storyboard();

    //New DoubleAnimation - Y
    DoubleAnimation translateYAnimation = new DoubleAnimation();
    translateYAnimation.From = this.Path[player.from, 1];
    translateYAnimation.To = this.Path[player.to, 1];

    translateYAnimation.EasingFunction = new ExponentialEase();
    translateYAnimation.EasingFunction.EasingMode = EasingMode.EaseOut;

    translateYAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));

    Storyboard.SetTarget(translateYAnimation, Piece);
    Storyboard.SetTargetProperty(translateYAnimation, 
           "(UIElement.RenderTransform).(CompositeTransform.TranslateY)");

    storyboard.Children.Add(translateYAnimation);

    //New DoubleAnimation - X 
    DoubleAnimation translateXAnimation = new DoubleAnimation();
    translateXAnimation.From = this.Path[player.from, 0];
    translateXAnimation.To = this.Path[player.to, 0];
    translateXAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));

    Storyboard.SetTarget(translateXAnimation, Piece);
    Storyboard.SetTargetProperty(translateXAnimation,
          "(UIElement.RenderTransform).(CompositeTransform.TranslateX)");

    storyboard.Children.Add(translateXAnimation);

    storyboard.Begin();

}

还有xaml中的按钮

<Button x:Name="Piece" Height="50" Width="50" HorizontalAlignment="Left" 
        Margin="115,400,0,0" VerticalAlignment="Top" Click="Button_Click" 
        RenderTransformOrigin="0.5,0.5">
    <Button.Template>
        <ControlTemplate>
            <Image Source="Assets/piece.png"/>
        </ControlTemplate>
    </Button.Template>
</Button>

1 个答案:

答案 0 :(得分:1)

我已经测试了您的代码,动画效果正常。您可以找到工作仓库on GitHub。由于代码几乎是示例的1:1副本,因此除外我对动画的FromTo属性值进行了硬编码。因此,我认为您看到的问题是this.Path[player.from, 0]this.Path[player.to, 0]的值相同(或非常相似)。这样,按钮会跳至this.Path[player.from, 0]位置并停留在该位置,而不会进一步移动。