获取BitmapImage对象的源路径

本文关键字:路径 对象 BitmapImage 获取 | 更新日期: 2023-09-27 17:53:34

我有一个使用MVVM, XAML和c#的Windows 8项目。

我的方法之一是目前更新的所有图像在图片文件夹中的ObservableCollection,转换为BitmapImage格式,这是绑定到我的xaml显示ListGrid中的图像。我遇到的问题是,我希望使用ListGrid中的SelectedItem属性来允许用户打开doubletapping的图片-要做到这一点,我需要在ObservableCollection中获得BitmapImages的路径。目前,当我尝试这样做时,UriSource属性被设置为null。我做错了什么?

这是填充我的ObservableCollection, "Images"的方法:

  private async void FindRelatedImages()
        {
            FileOpenPicker picPicker = new Windows.Storage.Pickers.FileOpenPicker();
            List<string> fileTypeFilter = new List<string>();
            fileTypeFilter.Add(".png");
            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".jpeg");
            fileTypeFilter.Add(".gif");
            fileTypeFilter.Add(".bmp");
            var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);
            StorageFolder folderToGetPicsFrom = KnownFolders.PicturesLibrary;
            var query = folderToGetPicsFrom.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList<StorageFile> fileList = await query.GetFilesAsync();
            // Process results
            ObservableCollection<BitmapImage> newList = new ObservableCollection<BitmapImage>();
            foreach (StorageFile file in fileList)
            {
                // Process file
                BitmapImage src = new BitmapImage( uriSource : new Uri(file.Path));
               // src.UriSource = new Uri(file.Path, UriKind.Absolute);
                src.SetSource(await file.OpenAsync(FileAccessMode.ReadWrite));
                newList.Add(src);
            }
            Images = newList;
        }

获取BitmapImage对象的源路径

我怀疑设置BitmapImage。UriSource到新Uri(file. path))的任意文件正在做任何事情,通过调用SetSource -你基本上覆盖了错误的设置。通常,如果你将UriSource设置为一个有效的源——你不需要在之后调用SetSource——这是加载图像的两种不同方法。

而不是使用ObservableCollection你可以使用类似ObservableCollection ItemViewModel有BitmapImage和StorageFile的属性。然后,您就有了将路径或文件传递到其他地方所需的一切。然后-为什么不只是传递BitmapImage本身在双击?如果你需要路径来打开一个WriteableBitmap的图像-为什么不直接从WriteableBitmap开始。如果你因为其他原因需要路径,你可以给ItemViewModel添加一个属性。