【问题标题】:Populating GridView with data from XML file使用 XML 文件中的数据填充 GridView
【发布时间】:2013-03-27 00:36:14
【问题描述】:

因此,在 Windows 8 平板电脑应用程序中,我有一个具有以下属性的 GridView:

    <Grid>
        <GridView ItemsSource="{Binding Source={StaticResource manager}, Path=TestStrings}" />
    </Grid>

链接到另一个类中的属性 TestStrings。

public List<string> TestStrings
    {
        get
        {
            List<Location> locations = getLocations(); 

            List<string> testStrings = new List<string>();

            for (int i = 0; i < locationList.Count; i++)
            {
                testStrings.Add(locationList[i].Name);
            }

            return testStrings;
        }
    }

    public async Task<List<Location>> getLocations()
    {
        return await xmlParser.getLocations();
    }

如果我只是用值填充一个字符串列表并返回它,GridView 会显示这些值,没问题。但是,问题是我需要调用异步方法。我的大部分数据将来自 XML 文件。要访问 XML 文件,我必须从存储中提取文件,据我所知,这需要我等待。这里,是那个方法:

public async Task<List<Location>> getLocations()
    {
        StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
        StorageFile file = await storageFolder.GetFileAsync("main.xml");
        XmlDocument xmlDoc= await XmlDocument.LoadFromFileAsync(file);
        XDocument xml = XDocument.Parse(xmlDoc.GetXml());

        List<Location> locationList =
            (from _location in xml.Element("apps").Elements("app").Elements("locations").Elements("location")
             select new Location
             {
                 Name = _location.Element("name").Value,
             }).ToList();

        return locationList;
    }

如您所见,我 await 两次,这迫使我将其设为异步方法,这意味着调用它的所有方法都必须是异步的。但是,XAML 中的绑定属性需要我访问一个不能异步的属性。

我觉得我错过了什么。我最近从 Android 转移到 Windows 8 中开始编程,所以很多对我来说都是新的。当然,将文件中的数据显示到 UI 是一项常见任务。最好的处理方法是什么?

【问题讨论】:

    标签: c# xaml windows-8


    【解决方案1】:

    尝试将列表类型从 List 更改为 ObservableCollection,看看是否能解决问题。您对异步行为的观察是正确的:对 List 的修改将不会触发绑定引擎通知任何已更改的内容,并且更改将在某个未知时间后发生。当您使用ObservableCollection 时,将出现该通知。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多