Site icon ParallelCodes

Xamarin Forms MVVM – How to use MessagingCenter

In this post we will implement Xamarin forms Messaging Center. The functionality of MessagingCenter uses a publish-subscribe pattern in which publisher sends a message without having any information or knowledge about any receiver, receiver is known as a subscriber. A subscriber will listen to messages sent with a key without having info about any publisher.

In the previous post we saw how to call Web API using Xamarin forms. If you are interested in learning it, please check it out.

So let’s start with this. In your Xamarin Forms project create two folders with name:

  1. Views
  2. ViewModels

Here we are skipping the Models folder as this example do not require any model classes.

Inside the Views folder add a layout xaml file as below:

Views > MainPage.xaml: 

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamSamples.Views.MainPage"
Title="Messaging Center Sample">

<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="5">

<Label Text="Enter a text to see MessagingCenter in action!" Margin="2"/>
<Entry Text="{Binding message}" HorizontalOptions="FillAndExpand" Margin="2" />

<Button Command="{Binding sendMessage}" Text="Send Message" Margin="2"
HorizontalOptions="FillAndExpand"/>

</StackLayout>

</ContentPage>

And edit the class as below

MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using XamSamples.ViewModels;

namespace XamSamples.Views
{
public partial class MainPage : ContentPage
{
VMMainPage mainPage;
public MainPage()
{
InitializeComponent();
mainPage = new VMMainPage();
BindingContext = mainPage;
}

protected override void OnAppearing()
{
try
{
MessagingCenter.Unsubscribe<VMMainPage, string>(this, "alert");
MessagingCenter.Subscribe<VMMainPage, string>(this, "alert",
(sender, arg) =>
{
DisplayAlert("Message from View", arg, "Ok");
});
}
catch (Exception ex)
{

}
}
}
}

Syntax:

MessagingCenter.Unsubscribe<VMMainPage, string>(this, "alert");
MessagingCenter.Subscribe<VMMainPage, string>(this, "alert",
(sender, arg) =>
{
DisplayAlert("Message from View", arg, "Ok");
});

The subscribe function will subscribe to "alert" messages that are sent be VMMainPage. This will listen to any message sent by VMMainPage class with ket as "alert", and will show a text message. The target action can be anything on receiving the valid message with proper key through MessagingCenter.

Now let’s start with the View Model. Create a class inside the ViewModels folder as shown below.

ViewModels > VMMainPage.cs

using Xamarin.Forms;

namespace XamSamples.ViewModels
{
public class VMMainPage : BaseViewModel
{
private string _message { get; set; }

public string message
{
get
{
return _message;
}
set
{
_message = value;
OnPropertyChanged();
}
}

public Command sendMessage { get; set; }

public VMMainPage()
{
message = "";
sendMessage = new Command(SendMessage);
}

public void SendMessage()
{
MessagingCenter.Send<VMMainPage, string>(this, "alert", message);
}

}
}

The SendMessage method will send out the string message with the key as "alert". Here we are taking the message value from the view. In our MainPage view, we have binded a text box using message variable. We will pass with value through MessagingCenter. It is necessary to unsubscribe to avoid multiple actions at a time which can be executed once a message is received. I have a practice when using MessagingCenter to unsubscribe to the ViewModels and its key to avoid any issues in the app.

Create one more class as below.

ViewModels > BaseViewModel.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace XamSamples.ViewModels
{
public class BaseViewModel : INotifyPropertyChanged
{

public virtual void OnAppearing()
{
}

protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName] string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;

backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}

#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;

changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion

}
}

This class is the base class for all our ViewModel classes.

Change the Main Page of your application by changing it in the App.xaml.cs.
App.xaml.cs:

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace XamSamples
{
public partial class App : Application
{
public App()
{
InitializeComponent();

MainPage = new NavigationPage(new Views.MainPage());
}

protected override void OnStart()
{
}

protected override void OnSleep()
{
}

protected override void OnResume()
{
}
}
}

Now run the app.

DOWNLOAD SOURCE CODE


Exit mobile version