将两个不同类型的list链接到一个ListView
本文关键字:链接 一个 list ListView 同类型 两个 | 更新日期: 2023-09-27 18:12:59
我正试图使ListView
显示图像和所选图像的名称。到目前为止,我已经成功地将List<BitmapImage>
绑定到ListView。ItemsSource显示ItemTemplate
中的Image
元素和Textblock
元素,我还成功地将每个Image
的名称添加到单独的List<string>
中。现在这就是我卡住的地方,我如何将List<BitmapImage>
和List<string>
绑定到单个ListView,因此每个列表项的尊重字段。
代码片段如下:
XAML视图:<ListView x:Name="listView_ViewPhotos" Visibility="Collapsed">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="0,5,0,5">
<Grid.ColumnDefinitions>
<!--Image Column-->
<ColumnDefinition Width="150"/>
<!--Name Column-->
<ColumnDefinition MinWidth="{Binding ActualWidth, ElementName=pageRoot, Mode=OneWay}"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding ImageList}" Height="100" Width="150" Stretch="UniformToFill" Grid.Column="0"/>
<TextBlock x:Name="txt_Listimg_Caption" Foreground="{ThemeResource ButtonForegroundThemeBrush}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="WrapWholeWords" Height="40" Margin="15,0,15,0" FontSize="25" Text="{Binding ImageName}" Grid.Column="1" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
c# public List<string> ImageName = new List<string>();
private async void appBar_GetFiles_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.List;
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".gif");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.FileTypeFilter.Add(".jpeg");
IReadOnlyList<StorageFile> filelist = await filePicker.PickMultipleFilesAsync();
foreach (var file in filelist)
{
if (file != null)
{
string FileName = file.Name;
//var imageData = await activeFolder.GetFileAsync(FileName);
//var imageData = await KnownFolders.PicturesLibrary.GetFileAsync(FileName);
BitmapImage bitmapImage;
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
}
ImageName.Add(FileName);
ImageList.Add(bitmapImage);
}
else break;
}
listView_ViewPhotos.ItemsSource = null;
listView_ViewPhotos.ItemsSource = ???;
gridView_ViewPhotos.ItemsSource = null;
gridView_ViewPhotos.ItemsSource = ???;
不用2个列表,只用1个:
首先,创建一个新类,命名为ImageDetails
。这个类包含2个属性,1是图像本身,1是图像的名称
public class ImageDetails
{
public BitmapImage Image{get;set:}
public string ImageName{get;set;}
}
现在,你不需要加载两个列表,只需调用List<ImageDetails>
添加示例:
List<ImageDetails> list = new List<ImageDetails>();
ImageDetails _imgDetails = new ImageDetails();
_imgDetails.Image = bitmapImage;
_imgDetails.ImageName = FileName;
list.Add(_imgDetails);
gettall示例:
foreach(var img in list)
{
var image = img.Image; //this is your BitmapImage
var name = img.ImageName; //this is your image Name
//other work
}