0

I'm trying to develop a .NET MAUI class library for folder picking. Following the instructions in Folder Picker .NET MAUI

  • firstly, I develop an interface:
public interface IAskDirectory
{
   Task<string> AskDirectory();
}
  • secondly, I created the file DirectoryAsker.cs and saved in Platform\Windows which contains
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;
        }
}

The first question is about the second step: how can I get the current Window handle? The "App" object (see line var hwnd = ...) is not recognized in a class library.

The second question is related to third step: interface registration with a generic host builder in the MauiProgram.cs. Is there a way to do this step in the class library or I have to do it every time in my main project, after having added the .dll to the references?

eljamba
  • 171
  • 1
  • 2
  • 11
  • If it isn't available, then caller must provide it. A straightforward way to do so, is to pass `App.Current` in as a parameter to the method. – ToolmakerSteve Nov 15 '22 at 22:32
  • I've found a NuGet package that does this now. I've added this info to an answer under the https://stackoverflow.com/a/76232496/1836461 question linked at the top of this question. – computercarguy May 12 '23 at 01:03

1 Answers1

0

If it isn't available, then caller must provide it. A straightforward way to do so, is to pass App.Current in as a parameter to the method:

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

...
public async Task<string> AskDirectory(Application app)
{
  ... app.Windows[0].Handler.PlatformView).WindowHandle;
ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196