Metro/Windows 8 + C#/XAML: How to find valid URIs to pictures stored in the Documents Library?

丶灬走出姿态 提交于 2019-12-08 06:22:19

问题


For Windows 8, I have created an app that downloads pictures from the web and stores them in programmatically created subfolders in the user's Document Library.

I have added the needed capabilities and declarations to the application manifest:

  • Documents Library enabled as a capability
  • File type association for jpg added and "open is safe" marked in declarations

When firing up the app, all folders and files are created correctly - and the user can open them manually from the file system.

My challenge is the following: when I programmatically load all available images and bind this list of images to XAML elements, I need a URI "xxx:///yyy/zzz.jpg" that can be used to set the image source correctly . I tried various schema flavours incl. "file:///yyy/zzz.jpg" but none succeeded.

Is there any way of doing this or is there no way at all?

When pictures are stored in the application data, XAML is happy with URIs like "ms-appdata:///local/zzz.jpg". But I definitely I would prefer to store pictures in the user's libraries.

Thanks for any help!


回答1:


If you are binding to the Image Source property, you cannot bind a file path. You must bind to a BitmapImage data type. If you were setting the Source property directly in code, it would look like this:

           BitmapImage bitmapImage = new BitmapImage();
            await bitmapImage.SetSourceAsync(fileStream);
            MyImage.Source = bitmapImage;

If you are binding to an object list, then the objects need to have a property on them that returns the BitmapImage data type (simplifying - you would need to support INotifyPropertyChanged as well):

public class MyDataBoundItem
{
   public BitmapImage MyBindableImage {get;set;}
}

You can enumerate the files in the Pictures folder with code like this...

var picFolder = Windows.Storage.KnownFolders.PicturesLibrary;
var options = new QueryOptions(CommonFileQuery.DefaultQuery,new List<string> { ".png", ".jpg" }) ;
options.FolderDepth = FolderDepth.Deep;

var query = picFolder.CreateFileQueryWithOptions(options);
var files = await query.GetFilesAsync();

The trick will be, and it depends on how you want to load your data, is to get the corresponding file from files into each of your databound objects so that it can provide the BitmapImage property. It's because the SetSourceAsync call being async that you will need to support INotifyPropertyChanged so the bound object can notify the UI when the image is available. Not hard, just not intuitively obvious.



来源:https://stackoverflow.com/questions/12235026/metro-windows-8-c-xaml-how-to-find-valid-uris-to-pictures-stored-in-the-docu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!