2013-03-27 74 views
0

因此,在Windows 8平板电脑的应用程序,我有以下属性一个GridView:填充GridView控件与XML文件中的数据

<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显示数据是一项常见任务。处理它的最好方法是什么?

回答

0

尝试更改列表的类型从ListObservableCollection,看看是否解决了问题。您对异步行为的观察是现场的:对列表的修改将而不是触发通知绑定引擎,任何事情都发生了变化,并且更改将在稍后的某个未知时间发生。当您使用ObservableCollection时,会发生该通知。