I have implemented tabbed navigation using FreshMVVM. When my app launches, I could notice that the 'ViewIsAppearing' method is getting invoked for all the tabs. However, if I switch to one tab, the 'ViewIsAppearing' method in its ViewModel is not getting called. If go to some other tab and switch back to this same tab, then it works. i.e. 'ViewIsAppearing' is not getting invoked in the initial tab change click. How do I make it invoke in the first attempt itself. I have come across a github issue similar to this. Just adding for reference https://github.com/xamarin/Xamarin.Forms/issues/3855
As suggested by @FreakyAli, I did a workaround by creating custom events 'OnAppearing' and 'OnDisappearing'. Its working fine so far. Code provided below. Please post your comments.
public class FreshBottomTabbedNavigationContainer:FreshTabbedNavigationContainer
{
private BasePageModel lastPageModel;
public FreshBottomTabbedNavigationContainer()
{
On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
this.CurrentPageChanged += FreshBottomTabbedNavigationContainer_CurrentPageChanged;
}
private void FreshBottomTabbedNavigationContainer_CurrentPageChanged(object sender, EventArgs e)
{
NavigationPage currentPage = (NavigationPage) ((FreshBottomTabbedNavigationContainer)sender).CurrentPage;
BasePageModel model = (BasePageModel)currentPage.RootPage.GetModel();
if (lastPageModel == null)
{
model.TriggerPageChangedEvent(new PageChangeEventArgs { CurrentPageModel = model });
}
else
{
model.TriggerPageChangedEvent(new PageChangeEventArgs { CurrentPageModel = model, LastPageModel = lastPageModel});
}
lastPageModel = model;
}
}
public class PageChangeEventArgs
{
public BasePageModel CurrentPageModel { get; set; }
public BasePageModel LastPageModel { get; set; }
}
public class BasePageModel : FreshBasePageModel
{
public event EventHandler OnAppearing;
public event EventHandler OnDisappearing;
public BasePageModel()
{
}
public void TriggerPageChangedEvent(PageChangeEventArgs e)
{
e.CurrentPageModel.OnAppearing?.Invoke(e.CurrentPageModel.CurrentPage, new EventArgs());
e.LastPageModel?.OnDisappearing?.Invoke(e.LastPageModel.CurrentPage, new EventArgs());
}
}
public class SamplePageModel : BasePageModel, INotifyPropertyChanged
{
public SamplePageModel()
{
OnAppearing += SamplePageModel_OnAppearing;
OnDisappearing += SamplePageModel_OnDisappearing;
}
private void SamplePageModel_OnDisappearing(object sender, EventArgs e)
{
}
private void SamplePageModel_OnAppearing(object sender, EventArgs e)
{
}
}