I'm using an MVVM approach. I have a ViewModel (let's call it Main) that needs to know via callback, event, etc. when navigation has returned to it from its child ViewModel. My attempted solution was to use MessagingCenter to alert my ViewModel upon the corresponding Page's OnAppearing call, like so:
In class MainPage:
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<Page>(this, "Main_OnAppearing");
}
And in class MainViewModel:
public MainViewModel()
{
MessagingCenter.Subscribe<Page>(this, "Main_OnAppearing", OnPageAppearing);
}
private void OnPageAppearing(object sender, Page page)
{
// Do stuff
}
This works, but with a problematic side effect that keeps me from sticking with it. If I back up to Main's parent ViewModel and then "re-enter" Main, my ViewModel/View "factory" will actually create a new ViewModel each time, so in this scenario 2 Main ViewModels now exist. Further, both of them have subscribed to MessagingCenter, and OnPageAppearing will then be called twice for each event, once for each ViewModel.
To make this approach work, I believe I would either need to unsubscribe from MessagingCenter or somehow force the destruction of the old/unneeded Main ViewModel when it and its Page are popped. But my best idea on how to do that would require the use of MessagingCenter, which would just lead to more of the same problem.
Can anyone advise on either how to fix this particular mess, or an alternate approach to my overall problem?