2012-06-27 74 views
1

我有一個包含TextBlock和圖像的元素的GridView。 TextBlock總是可以很好地填充,但Image偶爾會出現一個或兩個項目無法加載的情況。如果我刷新數據源,圖像將正確顯示。我認爲問題出在時間上(所有數據讀取都是異步完成的)。 這是從磁盤獲取圖像的代碼。所有圖像都是140x140像素,並且是PNG文件。爲什麼BitmapImages無法在我的GridView中正確加載和顯示?

public async Task<List<BitmapImage>> getPhotos() 
     { 
      photos.Clear(); //clears list of photos 

      IReadOnlyList<IStorageFile> files = (IReadOnlyList<IStorageFile>)await folderHierarchy.Last().GetFilesAsync(); //reads in all files from current working directory 

      foreach (StorageFile currentFile in files) //for each file in that directory 
      { 
       if (currentFile.Name.EndsWith(".png")) //only handle png files 
       { 
        photos.Add(await getBitmapImageAsync(currentFile)); //actually read in image from separate async method (bellow) 
       } 
      } 

      return photos; 
     } 

     public async Task<BitmapImage> getBitmapImageAsync(StorageFile storageFile) 
     { 
      BitmapImage image = new BitmapImage(); 
      FileRandomAccessStream stream = (FileRandomAccessStream) await storageFile.OpenAsync(FileAccessMode.Read); 
      image.SetSource(stream); 

      return image; 
     } 

我運行此方法使用:List tilePicturesArray = await dataFetcherClass.getPhotos(); 原始照片列表中不包含所有照片。在第一個代碼塊(上面)中發生了錯誤。 下一步是當我通過我的列表填充圖像和文本框(GridViewCell是我爲綁定GridView中的數據所做的一個類)GridViewCell對象的列表是綁定到我的GridView的。我不認爲這是問題。

for (int x = 0; x < tileTitlesArray.Count; x++) //this IS running inside of an async method 
      { 
       GridViewCell singleCell = new GridViewCell(); 

       singleCell.tileName = tileTitlesArray.ElementAt(x); 
       singleCell.tileImage = tilePicturesArray.ElementAt(x); 

       tileCells.Add(singleCell); //tileCells is the datasource for gridview 
      } 

您認爲會導致該問題?我添加了一個小刷新按鈕,基本上重新執行上述循環(重新填充gridview數據源和圖塊),但不重新讀取tilePicturesArray,因此綁定是使用相同的原始List of BitmapImages完成的(並且相同的圖塊仍然缺少圖片)

回答

1

發帖後約20分鐘,msdn論壇上的人回答了我的問題。大約一週前,這個問題困擾了我的計劃,但在過去的三天裏我才真正開始關注這個令人憤怒的問題。

如何修復:當從本地磁盤填充ListView或GridView數據綁定圖像時,請勿將流作爲BitmapImage源使用 - 使用帶有指向目標圖像的Uri對象的BitmapImage構造函數。

方法如下:

'的BitmapImage tempBitmap =新的BitmapImage(新的URI(currentFile.Path));

photos.Add(tempBitmap);`

相關問題