使用故事板在代码中设置矩形位置的动画

时间:2014-02-17 08:59:53

标签: c# xaml windows-phone-8 storyboard puzzle

我正在Windows Phone 8上制作c#/ xaml益智游戏。 我有一个行和列的网格,每个网格中都有一个矩形。 (我在运行时添加了这些矩形)

我已经有了一个代码,如果点击它,它会将一个矩形移动到另一个列或行。

我正在尝试使用故事板将此过渡变为平滑动画。

这是一个不起作用的代码,但显示了我想要做的事情。

    private void AnimateRectangle(Rectangle rectangle, int sourceColumn, int sourceRow, int targetColumn, int targetRow)
    {
        Storyboard s = new Storyboard();
        DoubleAnimation doubleAniColumn = new DoubleAnimation();
        doubleAniColumn.From = sourceColumn;
        doubleAniColumn.To = targetColumn;
        doubleAniColumn.Duration = new Duration(TimeSpan.FromMilliseconds(500));
        Storyboard.SetTarget(doubleAniColumn, rectangle);
        Storyboard.SetTargetProperty(doubleAniColumn, new PropertyPath("(Grid.SetColumn)"));

        DoubleAnimation doubleAniRow = new DoubleAnimation();
        doubleAniRow.From = sourceRow;
        doubleAniRow.To = targetRow;
        doubleAniRow.Duration = new Duration(TimeSpan.FromMilliseconds(500));
        Storyboard.SetTarget(doubleAniRow, rectangle);
        Storyboard.SetTargetProperty(doubleAniRow, new PropertyPath("(Grid.SetRow)"));

        s.Children.Add(doubleAniColumn);
        s.Children.Add(doubleAniRow);

        s.Begin();
    }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

嗯,你不能为Grid.Row属性设置动画,因为0.5没有意义。它是第0行或第1行。

你可以在这里做的是动画它的位置,并在完成更改行和列后。像这样:

private void AnimateRectangle(Rectangle rectangle, int sourceColumn, int sourceRow, int targetColumn, int targetRow)
{
rectangle.RenderTransform = new CompositeTransform();

    Storyboard s = new Storyboard();
    DoubleAnimation doubleAniColumn = new DoubleAnimation();
    doubleAniColumn.From = 0;
    doubleAniColumn.To = ...; // calculate correct offset here
    doubleAniColumn.Duration = new Duration(TimeSpan.FromMilliseconds(500));
    Storyboard.SetTarget(doubleAniColumn, rectangle);
    Storyboard.SetTargetProperty(doubleAniColumn, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateY)"));

    DoubleAnimation doubleAniRow = new DoubleAnimation();
    doubleAniRow.From = 0;
    doubleAniRow.To = ...; // calculate correct offset here
    doubleAniRow.Duration = new Duration(TimeSpan.FromMilliseconds(500));
    Storyboard.SetTarget(doubleAniRow, rectangle);
    Storyboard.SetTargetProperty(doubleAniRow, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)"));

    s.Children.Add(doubleAniColumn);
    s.Children.Add(doubleAniRow);

    EventHandler eventHandler = null;
    eventHandler = (sender, o) =>
    {
        s.Completed -= eventHandler;
        Grid.SetRow(rectangle, targetRow);
        Grid.SetColumn(rectangle, targetColumn);
        rectangle.RenderTransform = new CompositeTransform();
    };
    s.Completed += eventHandler;
    s.Begin();
}

我从头脑中编写了这段代码,所以不要介意一开始是不能编译的。