动画元素时的DoubleAnimation不会设置最终的Left和Top值

时间:2014-05-27 07:48:07

标签: windows-phone-8

我正在尝试使用DoubleAnimation动画/移动矩形。当这个动画完成时,我开始另一个DoubleAnimation,但第二个动画从矩形的初始位置开始(在第一个动画开始之前)。

这是XAML文件:

<Canvas>
    <Rectangle x:Name="myImage"
        Canvas.Left="10"
        Canvas.Top="10"
        Width="100"
        Height="100"
        Fill="Red">
    </Rectangle>
</Canvas>

这是cs文件:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        myImage.RenderTransform = new TranslateTransform();
        DoubleAnimation anima1 = new DoubleAnimation();
        anima1.Duration = TimeSpan.FromMilliseconds(2000);
        anima1.To = 150;

        Storyboard.SetTarget(anima1, myImage);
        Storyboard.SetTargetProperty(anima1, "(UIElement.RenderTransform).(TranslateTransform.X)");
        Storyboard storyboard = new Storyboard();
        storyboard.Children.Add(anima1);
        storyboard.Completed += storyboard_Completed;
        storyboard.Begin();
    }

    void storyboard_Completed(object sender, object e)
    {
        myImage.RenderTransform = new TranslateTransform();
        DoubleAnimation anima2 = new DoubleAnimation();
        anima2.Duration = TimeSpan.FromMilliseconds(2000);
        anima2.To = 150;
        Storyboard.SetTarget(anima2, myImage);
        Storyboard.SetTargetProperty(anima2, "(UIElement.RenderTransform).(TranslateTransform.Y)");
        Storyboard storyboard = new Storyboard();
        storyboard.Children.Add(anima2);
        storyboard.Begin();
    }

我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

您可以将Storyboard添加到单个Animation,并设置第二个动画的BeginTime属性,使其在第一个完成后启动,而不是使用2个Storyboard

//animation 1
myImage.RenderTransform = new TranslateTransform();
DoubleAnimation anima1 = new DoubleAnimation();
anima1.Duration = TimeSpan.FromMilliseconds(2000);
anima1.To = 150;

Storyboard.SetTarget(anima1, myImage);
Storyboard.SetTargetProperty(anima1, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));

//animation 2
myImage.RenderTransform = new TranslateTransform();
DoubleAnimation anima2 = new DoubleAnimation();
anima2.Duration = TimeSpan.FromMilliseconds(2000);
anima2.To = 150;
//delay anima2 for 2 seconds to make it begin after anima1 completed
anima2.BeginTime = TimeSpan.FromMilliseconds(2000);

Storyboard.SetTarget(anima2, myImage);
Storyboard.SetTargetProperty(anima2, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.Y)"));

Storyboard storyboard = new Storyboard();
storyboard.Children.Add(anima1);
storyboard.Children.Add(anima2);
storyboard.Begin();