我正在尝试开发一个用于文件夹选择的.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添加到引用后,我都必须在主项目中执行此步骤?
1条答案
按热度按时间unguejic1#
如果它不可用,那么调用者必须提供它。一个直接的方法是将
App.Current
作为参数传递给方法: