.NET MAUI文件夹选取器:类库实现

e4eetjau  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(383)

我正在尝试开发一个用于文件夹选择的.NET MAUI类库。

  • 首先,我开发了一个接口:
public interface IAskDirectory
{
   Task<string> AskDirectory();
}
  • 其次,我创建了文件 DirectoryAsker.cs 并保存在Platform\Windows中,其中包含
public class DirectoryAsker : IAskDirectory
{
        public async Task<string> AskDirectory()
        {
            var folderPicker = new FolderPicker();
            // Might be needed to make it work on Windows 10
            folderPicker.FileTypeFilter.Add("*");

            // Get the current window's HWND by passing in the Window object
            var hwnd = ((MauiWinUIWindow)App.Current.Windows[0].Handler.PlatformView).WindowHandle;

            // Associate the HWND with the file picker
            WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hwnd);

            var result = await folderPicker.PickSingleFolderAsync();

            return result?.Path;
        }
}

第一个问题是关于第二步的:如何获取当前窗口句柄?“App” 对象(见var hwnd = ...行)在类库中无法识别。
第二个问题与第三步有关:在MauiProgram.cs中使用泛型宿主构建器注册接口。是否有方法在类库中执行此步骤,或者每次在将.dll添加到引用后,我都必须在主项目中执行此步骤?

unguejic

unguejic1#

如果它不可用,那么调用者必须提供它。一个直接的方法是将App.Current作为参数传递给方法:

public interface IAskDirectory
{
   Task<string> AskDirectory(Application app);
}

...
public async Task<string> AskDirectory(Application app)
{
  ... app.Windows[0].Handler.PlatformView).WindowHandle;

相关问题