c# - UWP Storyboard 未正确执行动画
问题描述
我有一个小按钮,可以垂直和水平调整。我想使用 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>
解决方案
我已经测试了您的代码并且动画可以正常工作。您可以在 GitHub 上找到工作存储库。由于代码几乎是您的示例的 1:1 副本,除了我硬编码了动画的From
和To
属性值。因此,我认为您看到的问题是this.Path[player.from, 0]
值this.Path[player.to, 0]
相同(或非常相似)。这样按钮会跳转到该this.Path[player.from, 0]
位置并停留在那里,而不是进一步移动。