Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Phone, pick file using PickSingleFileAndContinue or PickMultipleFilesAndContinue

I got stuck trying to implementing file picker for windows phone app. I need to choose files from gallery using FileOpenPicker. I didn't get how it works. Here is my code:

private readonly FileOpenPicker photoPicker = new FileOpenPicker();

// This is a constructor
public MainPage()
{
    // < ... >

    photoPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    photoPicker.FileTypeFilter.Add(".jpg");
}

// I have button on the UI. On click, app shows picker where I can choose a file
private void bChoosePhoto_OnClick(object sender, RoutedEventArgs e)
{
    photoPicker.PickMultipleFilesAndContinue();
}

So, what to do next? I guess I need to get a file object or something.

I found this link. It is msdn explanation where custom class ContinuationManager is implemented. This solution looks weird and ugly. I am not sure if it is the best one. Please help!

like image 262
Andrei Avatar asked Jul 29 '14 08:07

Andrei


1 Answers

PickAndContinue is the only method that would work on Windows Phone 8.1. It's not so weird and ugly, here goes a simple example without ContinuationManager:

Let's assume that you want to pick a .jpg file, you use FileOpenPicker:

FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".jpg");
picker.ContinuationData.Add("keyParameter", "Parameter"); // some data which you can pass 
picker.PickSingleFileAndContinue();

Once you run PickSingleFileAndContinue();, your app is deactivated. When you finish picking a file, then OnActivated event is fired, where you can read the file(s) you have picked:

protected async override void OnActivated(IActivatedEventArgs args)
{
    var continuationEventArgs = args as IContinuationActivatedEventArgs;
    if (continuationEventArgs != null)
    {
        switch (continuationEventArgs.Kind)
        {
            case ActivationKind.PickFileContinuation:
                FileOpenPickerContinuationEventArgs arguments = continuationEventArgs as FileOpenPickerContinuationEventArgs;
                string passedData = (string)arguments.ContinuationData["keyParameter"];
                StorageFile file = arguments.Files.FirstOrDefault(); // your picked file
                // do what you want
                break;
        // rest of the code - other continuation, window activation etc.

Note that when you run file picker, your app is deactivated and in some rare situations it can be terminated by OS (little resources for example).

The ContinuationManager is only a helper that should help to make some things easier. Of course, you can implement your own behaviour for simpler cases.

like image 193
Romasz Avatar answered Oct 13 '22 13:10

Romasz