Task RunWindowTest <THandler>(IWindow window, Func <THandler, Task> action)
            where THandler : class, IElementHandler
        {
            return(InvokeOnMainThreadAsync(async() =>
            {
                var testingRootPanel = (WPanel)MauiProgram.CurrentWindow.Content;
                IElementHandler newWindowHandler = null;
                NavigationRootManager navigationRootManager = null;
                try
                {
                    var scopedContext = new MauiContext(MauiContext.Services);
                    scopedContext.AddWeakSpecific(MauiProgram.CurrentWindow);
                    var mauiContext = scopedContext.MakeScoped(true);
                    navigationRootManager = mauiContext.GetNavigationRootManager();
                    navigationRootManager.UseCustomAppTitleBar = false;

                    newWindowHandler = window.ToHandler(mauiContext);
                    var content = window.Content.Handler.ToPlatform();
                    await content.OnLoadedAsync();
                    await Task.Delay(10);

                    if (typeof(THandler).IsAssignableFrom(newWindowHandler.GetType()))
                    {
                        await action((THandler)newWindowHandler);
                    }
                    else if (typeof(THandler).IsAssignableFrom(window.Content.Handler.GetType()))
                    {
                        await action((THandler)window.Content.Handler);
                    }
                }
                finally
                {
                    if (navigationRootManager != null)
                    {
                        navigationRootManager.Disconnect();
                    }

                    if (newWindowHandler != null)
                    {
                        newWindowHandler.DisconnectHandler();
                    }

                    // Set the root window panel back to the testing panel
                    if (testingRootPanel != null && MauiProgram.CurrentWindow.Content != testingRootPanel)
                    {
                        MauiProgram.CurrentWindow.Content = testingRootPanel;
                        await testingRootPanel.OnLoadedAsync();
                        await Task.Delay(10);
                    }
                }
            }));
        }