0

因此,在 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;
    }

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

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

4

1 回答 1

0

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

于 2013-03-28T05:26:36.410 回答