Xamarin.Forms Simple example


Example

Here we will see a simple example of using the MessagingCenter in Xamarin.Forms.

First, let's have a look at subscribing to a message. In the FooMessaging model we subscribe to a message coming from the MainPage. The message should be "Hi" and when we receive it, we register a handler which sets the property Greeting. Lastly this means the current FooMessaging instance is registering for this message.

public class FooMessaging
{
    public string Greeting { get; set; }

    public FooMessaging()
    {
        MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
            this.Greeting = "Hi there!";
        });
    }
}

To send a message triggering this functionality, we need to have a page called MainPage, and implement code like underneath.

public class MainPage : Page
{
    private void OnButtonClick(object sender, EventArgs args)
    {
        MessagingCenter.Send<MainPage> (this, "Hi");
    }
}

In our MainPage we have a button with a handler that sends a message. this should be an instance of MainPage.