Posted on Leave a comment

Send signals between Mainpage.xaml.cs and Viewmodel – Xamarin.Forms

In a recent application I wanted to inform a Listview with a specific ItemTemplate to update its data source on back button with a synchronous data fetching mechanism(so this was not automatic).

So the goal was to send a “signal” to my Viewmodel when the page was loaded to perform an action. This can be done using MessageCenter with Xamarin.Forms.

The solution was to send an update signal every time OnAppearing() method of the MainPage.xaml was hit and inform the ViewModel to perfom an action.

 protected override void OnAppearing()
        {
            MessagingCenter.Send<nameofapp.App>((nameofapp.App)Xamarin.Forms.Application.Current, "update");
        }

Then perform action on MainPageViewModel

public MainPageViewModel()
        {
           
            MessagingCenter.Subscribe<nameofapp.App>((nameofapp.App)Application.Current, "update", (sender) => {
                var result = viewmodel.fetchData();
            });


        }