2017-01-22 46 views
0

我很新的C#和編程,試圖通過Head First C#書籍學習。 已經重新所著的碼好幾次,但仍然得到錯誤信息:參數2:無法從'字符串'轉換爲'System.Windows.PropertyPath'

錯誤CS1503參數2:無法從「字符串」轉換爲 「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(); 
     } 
    } 
    } 

回答

3

你沒有提供正確的參數類型的方法:第二個參數是PropertyPath型的,當你提供類型的對象string

的解決方案是簡單:

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

來源:MSDN

+0

謝謝,@ user3185569!它看起來像已解決但現在正在獲取消息 Storyboard.SetTargetProperty(animation,new PropertyPath(「propertyToAnimate」));然後試圖運行。一些建議?非常感謝! – Slava

+0

@Slava它應該是'new PropertyPath(propertyToAnimate)'不帶雙引號。 – user3185569

0

變化這樣的代碼,並嘗試

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

由於第二參數是的PropertyPath鍵入不串

+0

謝謝@Sreemat!它看起來像已解決,但現在正在獲取消息Storyboard.SetTargetProperty(animation,new PropertyPath(「propertyToAnimate」));然後試圖運行。一些建議?非常感謝! - – Slava

+0

無法讓你理解@Slava – Sreemat

+0

請檢查截圖:http://i67.tinypic.com/2ikxeti.png – Slava

相關問題