MessagingCenter to WeakReferenceMessenger

Jassim Al Rahma 1,616 Reputation points
2022-12-04T10:37:43.467+00:00

Hi,

How can I migrate from MessagingCenter to CommunityToolKit's WeakReferenceMessenger?

I have a simple code like this and I want to migrate it to WeakReferenceMessenger without MVVM?

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) =>  
{  
    // Do something whenever the "Hi" message is received  
});  

and:

MessagingCenter.Send<MainPage>(this, "Hi");  

Thanks,
Jassim

Developer technologies | .NET | .NET MAUI
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2022-12-05T02:52:18.753+00:00

    Hello,

    You could do it on MAUI by the following code:

       // Create Message object  
       public LoggedInStrChangedMessage(string str) : base(str)  
       {  
       }  
         
       // Register  
       WeakReferenceMessenger.Default.Register<LoggedInStrChangedMessage>(this, (r, m) =>  
       {  
           // Do something whenever the "Hi" message is received  
           Console.WriteLine("Hello!");  
       });  
         
       // Send  
       WeakReferenceMessenger.Default.Send(new LoggedInStrChangedMessage("Hi"));  
    

    please refer to Messenger to get more details.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.