c#wpf错误(System.InvalidOperationException)

时间:2017-01-08 00:14:09

标签: c# wpf

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

        public MainWindow()
        {
            InitializeComponent();
        }

        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()
            {
                From = from,
                To = to,
                Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6))),
            };
            Storyboard.SetTarget(animation, enemy);
            Storyboard.SetTargetProperty(animation, new PropertyPath(propertyToAnimate));
            storyboard.Children.Add(animation);
              //problem
            storyboard.Begin();
        }

    }

$ 我的错误(类型&#39; System.InvalidOperationException&#39;在PresentationFramework.dll中发生未处理的异常

其他信息:无法解析属性路径中的所有属性引用&#39;(canvas.left)&#39;。验证适用的对象是否支持属性。)

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

属性名称区分大小写。它应该是 C anvas。 L eft和 C anvas。 T 操作:

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);
}