1

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.

Cfun
  • 8,442
  • 4
  • 30
  • 62
ss1969
  • 99
  • 8
  • ou of curiosity why don't you close it from the code behind of the contentpage that opened it in the first place ? – Cfun Sep 24 '22 at 15:57
  • @ss1969 you expect to close the popup from the popup viewmodel? if this is not the case, why you want to close a popup from another viewmodel? if you Expect some result to close, first you should get that result and then you open or not the popup – Leandro Toloza Sep 27 '22 at 11:54

1 Answers1

3

I did this in my code

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