C#无法将项目添加到可观察集合中

时间:2014-04-07 12:54:36

标签: c# list windows-phone observablecollection items

我有一个问题,我试图将我的项目添加到我的observable集合,但我收到此错误:

参数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; }
}

2 个答案:

答案 0 :(得分:1)

尝试

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

gameDataList<GetGamesList>,因此您需要将gameData中的每个项目添加到Items列表中,因为ObservableCollection没有AddRange你需要在循环中手动完成它

答案 1 :(得分:-2)

您对cannot convert from 'System.Collections.Generic.List' to 'GameFinder.GetGamesList'的理解究竟是什么? Add方法接受单个元素,而您传入​​元素列表。您可以使用new ObservableCollection<GetGamesList>(gameData)。并删除Linq查询末尾的ToList语句。