popupmauiwindows-community-toolkitmaui-community-toolkit

How to close the MauiCommunityToolkit Popup from Viewmodel


I want close a CommunityToolkit Popup in my Viewmodel. I tried using a WeakReferenceMessenger to receive a message like this:

        public mypopup()
    {
        InitializeComponent();
        WeakReferenceMessenger.Default.Register<string, string>(this, "popup", (r, d) =>
        {
            Debug.WriteLine(message: "received message");
            if (d == "close")
            {
                WeakReferenceMessenger.Default.Unregister<string>(this);
                MainThread.BeginInvokeOnMainThread(() => { this.Close(); });
            }
        });
    }

And somewhere else I use this to send a message

WeakReferenceMessenger.Default.Send<string, string>("close", "popup");

The 1st call works. And the SECOND time it will raise a System.NullReferenceException in MauiPopup.windows.cs Function void CleanUp() Target.ContextFlyout = null;

I also tried like this in message receive:

MainThread.BeginInvokeOnMainThread(() => { this.Close(); });

the same happens. I wonder if there is a solution or a better way to close popup from somewhere else without transferring the handle of popup.


Solution

  • I did this in my code

            PopupPage p = new PopupPage();
            Application.Current.MainPage.ShowPopup(p);
            await new TaskFactory().StartNew(() => { Thread.Sleep(5000); });
            p.Close();