使用c# /Xaml在网格中显示可变数量的图像
本文关键字:图像 显示 Xaml 网格 使用 | 更新日期: 2023-09-27 17:50:56
我有一个方法,检索图像的绝对路径列表。我希望使用这些检索值来显示Windows 8应用程序内部的图像网格。需要注意的是,列表可以是任何大小,我希望图像填充屏幕并继续向下。
这似乎是一个非常简单的问题,但我找不到任何关于如何使用谷歌/必应做到这一点的明确答案-所以我说我将把它张贴在这里,希望有人知道在这种情况下该怎么做。
此刻,我只是从我的音乐文件夹中检索文件列表,并将它们附加到屏幕上显示的字符串-没有图像出现,我不知道如何使这个工作与动态数量的图像。有人能帮我一下吗?
到目前为止的代码:
检索音乐文件夹中的图像:
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();
}
和OutputTextBlock的XAML,它显示文件名,但不显示图像:
<Grid x:Name="Output" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">
<TextBlock x:Name="OutputTextBlock" Style="{StaticResource BasicTextStyle}" TextWrapping="Wrap"/>
</Grid>
我不确定这是否适用于Windows 8应用程序…但是在WPF中,我会尝试这样做:
<ItemsControl ItemsSource="{Binding Path=YourListOfPaths}"
HorizontalContentAlignment="Stretch">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ItemsControl
的ItemsSource
绑定到您的文件路径列表(例如ObservableCollection<string>
), ItemTemplate
描述如何显示每个单独的项目-我只是为每个单独的文件使用Image
控件。Source
被绑定到项目本身(这里是一个单独的文件路径)。