参数2:无法从'string'转换为'System.Windows.PropertyPath'

时间:2017-01-22 18:07:05

标签: c#

我是C#和编程的新手,试图通过Head First C#book学习。 已经多次重新编写代码,但仍然收到错误消息:

  

错误CS1503参数2:无法从'string'转换为   'System.Windows.PropertyPath'

非常感谢帮助:)

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace Save_The_Humans
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Random random = new Random();
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button_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, propertyToAnimate);//THIS IS A PROBLEMATIC LINE, the "propertyToAnimate" is underlined.
            storyboard.Children.Add(animation);
            storyboard.Begin();
        }
    }
    }

2 个答案:

答案 0 :(得分:3)

您未向方法提供正确的参数类型:第二个参数的类型为PropertyPath,而您提供类型为string的对象。

解决方案很简单:

Storyboard.SetTargetProperty(animation, new PropertyPath(propertyToAnimate));

来源:MSDN

答案 1 :(得分:0)

更改此代码并尝试

 Storyboard.SetTargetProperty(animation,new PropertyPath(propertyToAnimate));

由于第二个参数是PropertyPath类型而不是字符串