Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnAppearing event firing twice .with tabbed page

I am facing issue being a beginner for Xamarin forms and MVVM . I have tabbedpage and 2 pages are under tag . Here is code.

Issue is local:ActiveOrderViewPage page OnAppearing() event is firing twice when tabbedPage is loading and execute twice code under OnAppearing() event .

Please help me to find this why this is happening ?

Here Is code Tabbed Page tabbedpage.xaml

<TabbedPage
        xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        Title="Orders">
<TabbedPage.Children>  
      <local:ActiveOrderViewPage />  
      <local:SavedOrderViewPage />
</TabbedPage.Children>

tabbedpage.xaml.cs

  public partial class OrderTabViewPage : TabbedPage
{
    public OrderViewModel ViewModel { get { return BindingContext as OrderViewModel; } }
    public OrderTabViewPage()
    {
        InitializeComponent();
     this.BindingContext = ViewModelLocator.OrderVModel;

    }
    public OrderTabViewPage(params object[] arg) : this()
    {
        if (arg != null)
        {
            ViewModel.AccountID = Convert.ToInt32(arg[0]);
        }
    }

Here is active order .cs

 public partial class ActiveOrderViewPage : ContentPage
{
    public OrderViewModel ViewModel { get { return BindingContext as OrderViewModel; } }
    public ActiveOrderViewPage()
    {
        InitializeComponent();
      this.BindingContext = ViewModelLocator.OrderVModel;       
    }

    //public OrderViewPage() : this()
    //{
    //    ViewModel.AccountID = accuntId;
    //}
    protected override void OnAppearing()
    {
        base.OnAppearing();
        if (ViewModelLocator.OrderVModel.ActiveOrderItems == null || ViewModelLocator.OrderVModel.ActiveOrderItems.List.Count == 0)
        {
            ViewModelLocator.OrderVModel.ActiveOrderCommand.Execute(null);
        }


    }

Thanks in advance ...

like image 675
user2797910 Avatar asked Oct 30 '22 22:10

user2797910


1 Answers

Having had this problem for a long long time, before realising, I know how frustrating this is. The event OnAppearing() fires twice because of the way that the tabbed page renders all of the individual pages. It initially renders the page, then in your case will render the other page, which causes the OnDisappearing() to fire. The first page then gets focus, causing the OnAppearing() to fire again.

If you only want the code to fire once, after adding the child pages, set the currentpage property to null, which should stop the OnAppearing() from firing again

like image 161
Behavior Avatar answered Nov 17 '22 00:11

Behavior