Messaging Center in Xamarin Forms

What is Messaging Center?

Xamarin forms gives an option for communication between models and other components to communicate between them without knowing anything of each other. This communication is done by a simple contract between messages.

Explanation:

Following are the main parts of messaging center.

Send:

Sender is one who is going to send a messages to all of its subscribers. This message is send by giving arguments and without giving arguments. If there is no subscriber of message than it is ignored.

Subscribe:

Subscriber is one who is interested to receive messages by sender. Subscriber is open to listen for messages send by a sender.

Unsubscribe:

You also have an option to unsubscribe any message. When there is no need of message you can simply unsubscribe it.

Example:

Lets go through a simple example of sending messages through messaging center. In this example there are two pages. One is “MainPage” and second is “SecondPage”. Now in this example we can send a message from “MainPage” to “SecondPage” when the button is clicked.

Sender Code:

With String Argument:

void ButtonClicked(object sender, EventArgs ea)
 {
Navigation.PushAsync( new SecondPage());
MessagingCenter.Send<MainPage, string>(this, "HelloMessage", "Welcome to Xamarin Web");
}

 

Here Message is send from MainPage with Message id of “HelloMessage” and a string argument.

If you want to send message without passing any argument.

Without any argument:

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

 

Subscriber Code:

With String Argument:

public partial class SecondPage : ContentPage
 {
 public SecondPage ()
 {
 InitializeComponent ();
 MessagingCenter.Subscribe<MainPage,string>(this, "HelloMessage",(sender,a)=> { label.Text = a; });
 }
 }

 

Here the Subscriber subscribes “HelloMessage” coming from ‘MainPage’. and set the string parameter to its label text.

Without Argument:

MessagingCenter.Subscribe<MainPage>(this, "HelloMessage",(sender)=> {

//Do whatever you want when HelloMessage calls.

});

 

Output:

 

And When you click on a button you are navigated to second page with message.

 

Here we are almost done and send a simple message through messaging center.

 

Unsubscribe:

If you want to unsubscribe message at any time than just code one more line.

MessagingCenter.Unsubscribe<MainPage>(this, "HelloMessage");

 

This will unsubscribe the “HelloMessage” coming from MainPage.

 

XamarinWeb Founder | MVP – C-SharpCorner | Xamarin Forms Developer

One comment

Leave a Reply to vipin Cancel reply

Your email address will not be published. Required fields are marked *