我正在try 在Windows App SDK(WinUI3)应用程序中显示文件选取器.我正在用C#编写它.
下面是显示文件选取器的函数:
private async Task<StorageFile> PickFileAsync()
{
var filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.FileTypeFilter.Add(".jpg");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".png");
var hwnd = this.XamlRoot.Content.XamlRoot.WindowId;
WinRT.Interop.InitializeWithWindow.Initialize(filePicker, hwnd);
StorageFile file = await filePicker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
return file;
}
else
{
return null;
}
}
下面是我调用该函数的方式:
StorageFile pickedFile = await PickFileAsync();
以防万一,我从定义为private
、async
和void
的另一个函数中调用该函数.
顺便说一句,我已经将PickFileAsync()
方法放入了我的一个应用程序页面的.cs
代码中,因为该页面包含触发操作的菜单.
很少有文章说明这一点,所以我不能真正做太多的研究.