2013-03-27 32 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時,會發生該通知。