Forum Xamarin.Forms

How to MessagingCenter.Subscribe to same message from multiple senders

cmeerencmeeren USMember ✭✭
edited September 2016 in Xamarin.Forms

I want to subscribe to a message that can be sent from multiple ViewModels. Is there a more elegant solution than subscribing individually for each ViewModel, like I do below?

MessagingCenter.Subscribe<Page1Model, bool>(this, "SomeMessage", MyMethod);
MessagingCenter.Subscribe<Page2Model, bool>(this, "SomeMessage", MyMethod);

Best Answer


  • cmeerencmeeren USMember ✭✭

    If I were to use Application, then I'm tying my view models to my view. Also, it becomes harder to test the VMs directly.

    Thanks for the tip on using domain-specific models, I'll keep that in mind.

  • Nicolas.BodinNicolas.Bodin USMember ✭✭

    The @RobertMcIntosh answer is really good but I want to share my solution :)

    Like the accepted answer I wrap the MessagingCenter inside my own class :

    void SubscribeToDoAction<T>() where T : class
        MessagingCenter.Subscribe<T>(this, "message", (sender) => 
            ( your action ... )

    The way to send the message is exactly the same as usual, it does not matter what class is sending (Sender1, Sender2, ...)

    MessagingCenter.Send(this, "message");

    And I subscribe to it like this :


  • JassimRahmaJassimRahma USMember ✭✭✭✭

    I am still not clear on this guys

    I want to Send:

    MessagingCenter.Send(this, "Country", country_code);


    MessagingCenter.Send(this, "Country", country_name);

    to the Signup page

    How can I do that please?

Sign In or Register to comment.