I am using MessagingCenter to passe objects throu my pages, from my LoginPage to my MainPage.
Even tho the object is updated, when using it to my mainpage, the object seems to be null.
public User sUser { get; set; }
public MainPage()
{
InitializeComponent();
MessagingCenter.Subscribe<LoginPage, User>(this, "currentUserMainPage", (obj, item) =>
{
sUser = item;
Debug.WriteLine("User updated from mainPage: " + sUser.firstName);
});
MasterBehavior = MasterBehavior.Popover;
MenuPages.Add((int)MenuItemType.Home, (NavigationPage)Detail);
}
When I check for the object before changing pages, even tho it is not null anymore, it returns me null.
public async Task NavigateFromMenu(int id)
{
if (!MenuPages.ContainsKey(id))
{
switch (id)
{
case (int)MenuItemType.Profile:
if(sUser == null)
{
MenuPages.Add(id, new NavigationPage(new LoginPage(sUser)));
}
else
{
MenuPages.Add(id, new NavigationPage(new ProfilePage(sUser)));
}
break;
}
}
}
Any idea what am I missing here?
Edit: here is the call from the LoginPage
protected override async void OnAppearing()
{
base.OnAppearing();
try
{
//perform login
MessagingCenter.Send(this, "currentUserMainPage", aUser.User);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
First you can have a check with MessageCenter document : https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center
When subscribing and sending message , we need to keep the count and type of paramater be the same .
The example as follow :
Publish a Message :
MessagingCenter.Send<MainPage, string>(this, "Hi", "John");Subscribe to a message :
You will see that the first paramater is
MainPage, and the second isstring. They all need to set when publishing or subscribing .In addition , using MessageCenter between different pages or classes , you can use
objectto replace orMainPage.Therefore , shared code can be modified as follow :
Subscribing MessageCenter with
object:And send message also with
object: