简体   繁体   中英

Launching a FilePicker or FolderPicker from a UICommand / MessageDialog

When my Windows Store app starts I want to prompt the user to choose a local storage folder using FolderPicker and saving it with FutureAccessList . The prompt I use is a MessageDialog .

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    var messageDialog = new MessageDialog("Please pick a folder where you'd like to store your documents", "Choose storage");
    messageDialog.Commands.Clear();
    messageDialog.Commands.Add(new UICommand("OK", async (command) =>
    {
        await PickFolder();
    });
    await messageDialog.ShowAsync();
}

private async Task PickFolder()
{
    FolderPicker folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
    folderPicker.FileTypeFilter.Add(".txt");
    folder = await folderPicker.PickSingleFolderAsync();
    // lets just ignore cancellations for now
    StorageApplicationPermissions.FutureAccessList.AddOrReplace("MyFolder", folder);
}

This code doesn't work - I get an Access denied error

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

I thought using messageDialog.ShowAsync() was enough to get around this but it doesn't seem to work. Any ideas?

Do I have to abandon the pretty WinRT messageDialogs in favor of something home grown?

The MessageDialog's command fires before it closes, and you can't open a second modal dialog while the first is still up.

You need to delay the call to PickFolder until after the MessageDialog has completed. Since you're awaiting it anyway you can call it after the ShowAsync. It's moot here since ok is the only option, but you can switch on the command chosen to pick between multiple options.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    var messageDialog = new MessageDialog("Please pick a folder where you'd like to store your documents", "Choose storage");
    messageDialog.Commands.Clear();
    UICommand okCommand = new UICommand("Ok");
    messageDialog.Commands.Add(okCommand);
    var cmd = await messageDialog.ShowAsync();
    if (cmd == okCommand)
    {
        await PickFolder();
    }
}

Another option would be to add a delay (eg by calling PickFolder in a Dispatcher.RunAsync block) within the UICommand handler before calling PickFolder so that the MessageDialog can close.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM