2013-01-08 25 views
1

我有一種方法可以檢索圖像的絕對路徑列表。我希望使用這些檢索值在Windows 8應用程序中顯示圖像網格。需要注意的是,該列表可以是任何大小,我希望圖像填滿屏幕並繼續向下。使用C#/ Xaml在網格中顯示可變數量的圖像

這似乎是一個非常簡單的問題,但我無法找到任何關於如何使用Google/Bing執行此操作的明確答案 - 所以我說過我會在此處發佈它,以避免有人知道該怎麼做案件。

目前,我只是從我的音樂文件夾中檢索文件列表,並將它們附加到顯示在屏幕上的字符串 - 沒有圖像出現,我不知道如何使用這個工作動態數量的圖像。任何人都可以幫助我嗎?

代碼迄今:

檢索在音樂文件夾圖片:

private async void SearchButton_Click(object sender, RoutedEventArgs e) 
     { 
      StorageFolder musicFolder = KnownFolders.MusicLibrary; 

      List<string> fileTypeFilter = new List<string>(); 
      fileTypeFilter.Add(".png"); 

      QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, fileTypeFilter); 
      //use the user's input to make a query 
      queryOptions.UserSearchFilter = InputTextBox.Text; 
      StorageFileQueryResult queryResult = musicFolder.CreateFileQueryWithOptions(queryOptions); 

      StringBuilder outputText = new StringBuilder(); 

      //find all files that match the query 
      IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync(); 
      //output how many files that match the query were found 
      if (files.Count == 0) 
      { 
       outputText.Append("No files found for '" + queryOptions.UserSearchFilter + "'"); 
      } 
      else if (files.Count == 1) 
      { 
       outputText.Append(files.Count + " file found:\n\n"); 
      } 
      else 
      { 
       outputText.Append(files.Count + " files found:\n\n"); 
      } 

      //output the name of each file that matches the query 
      foreach (StorageFile file in files) 
      { 
       outputText.Append(file.Name + "\n"); 
      } 

      OutputTextBlock.Text = outputText.ToString(); 
     } 

和顯示文件名的XAML OutputTextBlock,但沒有圖像:

<Grid x:Name="Output" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top"> 
    <TextBlock x:Name="OutputTextBlock" Style="{StaticResource BasicTextStyle}" TextWrapping="Wrap"/> 
</Grid> 

回答

1

我不知道這是否會適用於Windows 8應用程序...但在WPF中,我會嘗試像這樣:

<ItemsControl ItemsSource="{Binding Path=YourListOfPaths}" 
       HorizontalContentAlignment="Stretch"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Image Source="{Binding}" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

ItemsControlItemsSource被綁定到您的文件路徑列表(例如:一個ObservableCollection<string>),ItemTemplate描述了每個單個項目的顯示方式 - 我對每個單個文件都使用了一個Image控件。 Source綁定到項目本身(這裏是單個文件路徑)。