Razor Razor - 1 month ago 7
C# Question

Cast variable as an ItemSource for a LongListViewer

I have a variable named

items
that finds a set of descendants of an XML element and binds them to a
TextBlock
on a
LongListViewer
in Windows Phone 8.1 Silverlight. When I go and try to set the
ItemSource
with this variable, it comes up with an error:


Cannot implicitly convert type
System.Collections.Generic.IEnumerable<Lists.ListsXmlBinder>
to
System.Collections.IList
. An explicit conversion exists (are you
missing a cast?)


Here is my code:

using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (Stream stream = storage.CreateFile("list.xml"))
{
XDocument document = XDocument.Load(stream);
document.Element("lists").Add(new XElement("list", new XElement("name", "random list"), new XElement("date", DateTime.Now.ToString())));
document.Save(stream);

var items = from query in document.Descendants("list")
select new ListsXmlBinder
{
Name = query.Element("name").Value,
Date = query.Element("date").Value
};

lists_ListViewer.ItemsSource = items;
}
}


Any suggestions on how to solve the problem?

Answer

Just add a call to ToList() to convert the IEnumerable to a list:

var items = (from query in document.Descendants("list")
                            select new ListsXmlBinder
                            {
                                Name = query.Element("name").Value,
                                Date = query.Element("date").Value
                            }).ToList();
Comments