Head First C# - 第1章属性动画不起作用

时间:2016-05-05 03:58:20

标签: c#

我目前正在完成这个课程Head First C#并且在第一课结束时遇到困难,最后一个错误仍然存​​在且我不知道如何解决它,请你们中的一些人帮忙吗?

谢谢,真的很感激

enter image description here

这是有问题的代码...动画的属性就在它的末尾      Storyboard.SetTargetProperty(animation,propertyToAnimate);

    using System;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;

    using System.Windows.Media.Animation;



    namespace Save_The_Human
    {   
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Random random = new Random();
        private double To;

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            AddEnemy();
        }
        private void AddEnemy()
        {
            ContentControl enemy = new ContentControl();
            enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
            AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
            AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
                random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
            playArea.Children.Add(enemy);
        }

        private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
        {
            Storyboard storyboard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
            DoubleAnimation animation = new DoubleAnimation();
            {
                var From = from;
                To = to;
                var Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)));
            };
            Storyboard.SetTarget(animation, enemy);
            Storyboard.SetTargetProperty(animation, propertyToAnimate);
            storyboard.Children.Add(animation);
            storyboard.Begin();
        }   
    }

}

1 个答案:

答案 0 :(得分:1)

在某些版本的.NET或类似版本中看起来像是一个重大变化。

您可以通过替换AnimateEnemy方法的声明并调用它来修复它:

...
AnimateEnemy(enemy, 0, playArea.ActualWidth - 25, new PropertyPath("(Canvas.Left)"));
AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 25), random.Next((int)playArea.ActualHeight - 25), new PropertyPath("(Canvas.Top)"));
...
private void AnimateEnemy(ContentControl enemy, double from, double to, PropertyPath propertyToAnimate)
...