日期:2014-05-17  浏览次数:20782 次

LINQ for XML数据传递失败,请高人帮忙。
根据VS2012的模板,修改了一个Windows apps类:SampleDataSource。大意是从XML文件读取数据, 用到了LINQ for XML,然后添加到group1.Items中。
但是代码运行完后,group1.Items总是为空,不能生成数据。好像是IEnumerable<XElement> _els没有 new的原因?对C#不是很精通,不清楚是什么原因,会不会是数据传递时出错了呢,请大家帮忙,谢谢!
附上代码如下: 

using Windows.Storage;
using System.Xml.Linq;
using System.IO;
        
        public sealed class SampleDataSource
        {
            private IEnumerable<XElement> _els;

            public async void setgroupedItemsViewSource()
            {
                var picturesLibrary = Windows.Storage.KnownFolders.PicturesLibrary;
                Windows.Storage.StorageFile file = await picturesLibrary.GetFileAsync(@"file.xml");

                XDocument doc1 = new XDocument();
                using (Stream stream = await file.OpenStreamForReadAsync())
                {
                    doc1 = XDocument.Load(stream);
                }
                var els = from el in doc1.Root.Elements()
                          select el;
                this._els = els;
            }

            public SampleDataSource()
        {
            setgroupedItemsViewSource();
            foreach (XElement el in this._els)
             {
                  group1.Items.Add(new SampleDataItem((string)el.Attribute("id"));
             }

            }
        }

------最佳解决方案--------------------
把你的 
foreach (XElement el in this._els)
{
     group1.Items.Add(new SampleDataItem((string)el.Attribute("id"));
}
移到 setgroupedItemsViewSource 里,其他不用动。
------其他解决方案--------------------
se