user10778279
user10778279

Reputation:

How to load data in TabbedPage when a tab is clicked?

I am using TabbedPage for navigation with tabs. All my Page classes have just an empty default constructor and I load my data in the OnAppearing method. I have 5 tabs. As soon as I click on the second tab, the OnAppearing methods of the 3rd, 4th and 5th pages are also called.

How do I ensure that the data is only loaded when I click on the tab?

Upvotes: 1

Views: 2000

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

Solution:

You can get the index of currentPage in method OnCurrentPageChanged And if the index equals 1(second page) , use the messagecenter to send message to the page.Refer the following code .

in Tabbed Page

protected override void OnCurrentPageChanged()
{
   base.OnCurrentPageChanged();

   int index = Children.IndexOf(CurrentPage);

   if (index == 1)
   {
      MessagingCenter.Send<Object>(this, "click_second_tab");
   }

   else if (index == 2)
   {
      MessagingCenter.Send<Object>(this, "click_third_tab");
   }


} 

in the second page .Move the code that load data from onAppearing to the constructor

public MyPage1()
{

  //...
  MessagingCenter.Subscribe<Object>(this, "click_second_tab", (obj) =>
  {
     //load your data here

      Console.WriteLine("11111");
  });

} 

Upvotes: 3

Related Questions