我正在使用该代码来选择一个文件夹,它工作得很好。
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
StorageFolder pickedFolder = await folderPicker.PickSingleFolderAsync();
但是当我在特定功能中使用它时,我不知道为什么突然不起作用了。
这就是我从按钮单击到FolderPicker弹出窗口的全部操作。
按钮单击:
private async void BRechercherPoste_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (tbCodePoste != null && !tbCodePoste.Text.Equals(""))
{
string codePoste = tbCodePoste.Text;
//recuperation des infos du poste
await ViewModel.getPosteInformationsAsync(codePoste);
}
}
...然后是ViewModel.getPosteInformationsAsync
:
public async Task getPosteInformationsAsync(string posteNumber)
{
ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
await setupFiles();
[some code not interferring here]
}
... setupFiles:
public static async Task setupFiles()
{
//checks for the first time app launch
if (!await checkIfPosteFolderPresentAsync())
{}
PosteChoiceDialog dialogChoice = new PosteChoiceDialog();
//showing a dialog with 2 choices
await dialogChoice.ShowAsync();
}
[rest of the code (working)]
}
因此该对话框显示2个选择,一个将默认数据加载到LocalFolder
中,另一个使您选择一个个人文件夹将数据加载到LocalFolder
中。
选择第二个选项时触发的功能是:
public static async Task loadCustomPosteInformation()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
//---Here the folder picker open and closes instantly for no reason---//
StorageFolder pickedFolder = await folderPicker.PickSingleFolderAsync();
//--------------------------------------------------------------------//
//Because it's not working the rest of the function crashes
if (pickedFolder == null)
{
await loadDefaultPosteInformation();
}
else
{
var files = await pickedFolder.GetFilesAsync();
StorageFolder postes = await localFolder.CreateFolderAsync("Postes");
foreach (StorageFile f in files)
{
await f.CopyAsync(postes);
}
}
}
所以我详细介绍了所有可能的信息,因为我花了几个小时搜索它崩溃的原因,而且我真的不明白为什么FolderPicker
仅在该特定函数中始终立即关闭。
答案 0 :(得分:1)
可能与PickSingleFolderAsync()
调用不在UI线程中有关,尽管如果是这种情况,我不知道为什么它会首先打开(或关闭)。
仍然,为什么不尝试从UI线程调用StorageFolder.PickSingleFolderAsync()
:
StorageFolder pickedFolder;
var completionSource = new TaskCompletionSource<StorageFolder>();
var folderDialogTask = completionSource.Task;
Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.High,
async () =>
{
var folder = await folderPicker.PickSingleFolderAsync();
completionSource.SetResult(folder);
});`
pickedFolder = await folderDialogTask;