2014-04-07 116 views
0

我有哪裏我嘗試我的項目添加到我的觀察到的集合問題,但我得到這個錯誤:C#無法將項目添加到觀察的集合

參數1:無法從「System.Collections.Generic轉換.LIST」到 'GameFinder.GetGamesList'

代碼:

private void RequestCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 

     if (e.Error == null) 
     { 
      var feedXml = XDocument.Parse(e.Result); 

      var gameData = feedXml.Root.Elements("Game").Select(x => new GetGamesList 
      { 
       ID = (int)x.Element("id"), 
       GameTitle = (string)x.Element("GameTitle"), 
       ReleaseDate = (string)x.Element("ReleaseDate"), 
       Platform = (string)x.Element("Platform") 
      }) 
       .ToList(); 
      Items.Add(gameData); // THE ERROR IS HERE - Items is the observablecollection 
     } 
    } 

private ObservableCollection<GetGamesList> _Items = new ObservableCollection<GetGamesList>(); 
    public ObservableCollection<GetGamesList> Items 
    { 
     get 
     { 
      return this._Items; 
     } 
    } 

public class GetGamesList 
{ 
    public int ID { get; set; } 
    public string GameTitle { get; set; } 
    public string ReleaseDate { get; set; } 
    public string Platform { get; set; } 
} 

回答

1

嘗試

foreach (var item in gameData) Items.Add(item) 

gameDataList<GetGamesList>所以你需要的每個項目gameData加入到Items列表,因爲ObservableCollection沒有AddRange你需要做手工的循環

+0

或者請參閱[this](http://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each) –

+0

謝謝它的作品:)。我想將oberservable集合Items綁定到我的LongListSelector,但它不起作用。在我的xaml中,我這樣做:ItemsSource =「{Binding Items}」有什麼想法爲什麼?謝謝。 – Thunder

+0

假設'DataContext'沒問題,我沒有看到爲什麼綁定不起作用的原因 – dkozl

-2

究竟你不上cannot convert from 'System.Collections.Generic.List' to 'GameFinder.GetGamesList'明白了嗎?添加方法接受單個元素,而傳遞元素列表。您可以使用new ObservableCollection<GetGamesList>(gameData)。並在您的Linq查詢結束時刪除ToList語句。

+0

親愛的Vasek,歡迎來到SO,請閱讀以下鏈接:http://stackoverflow.com/help/how-to-answer –

+0

我明白錯誤信息,但我不知道如何解決它。 – Thunder