我有一个问题,我试图将我的项目添加到我的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; }
}
答案 0 :(得分:1)
尝试
foreach (var item in gameData) Items.Add(item)
gameData
是List<GetGamesList>
,因此您需要将gameData
中的每个项目添加到Items
列表中,因为ObservableCollection
没有AddRange
你需要在循环中手动完成它
答案 1 :(得分:-2)
您对cannot convert from 'System.Collections.Generic.List' to 'GameFinder.GetGamesList'
的理解究竟是什么? Add方法接受单个元素,而您传入元素列表。您可以使用new ObservableCollection<GetGamesList>(gameData)
。并删除Linq查询末尾的ToList
语句。