[英]Xamarin Forms Tabbed Page Load Data when tab is Select
我在 Xamarin 表單中有一個 TabbedPage,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:AppName.Views.Main"
xmlns:Search="clr-namespace:AppName.Views.Search"
x:Class="AppName.Views.Main.BottomNavigationPage"
xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
android:TabbedPage.ToolbarPlacement="Bottom"
android:TabbedPage.BarSelectedItemColor="{DynamicResource PrimaryColor}"
android:TabbedPage.BarItemColor="{DynamicResource Gray-600}"
android:TabbedPage.IsSwipePagingEnabled="False"
BarBackgroundColor="White"
NavigationPage.HasNavigationBar="False">
<TabbedPage.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</TabbedPage.Resources>
<local:HomePage Title="">
<local:HomePage.IconImageSource>
<FontImageSource FontFamily="{StaticResource FASolid}"
Glyph=""
Size="10"/>
</local:HomePage.IconImageSource>
</local:HomePage>
<Search:ExplorePage Title="">
<Search:ExplorePage.IconImageSource>
<FontImageSource FontFamily="{StaticResource FASolid}"
Glyph=""
Size="10"/>
</Search:ExplorePage.IconImageSource>
</Search:ExplorePage>
<local:PhotosPage Title="">
<local:PhotosPage.IconImageSource>
<FontImageSource FontFamily="{StaticResource FASolid}"
Glyph=""
Size="10"/>
</local:PhotosPage.IconImageSource>
</local:PhotosPage>
<local:SettingsPage Title="">
<local:SettingsPage.IconImageSource>
<FontImageSource FontFamily="{StaticResource FASolid}"
Glyph=""
Size="10"/>
</local:SettingsPage.IconImageSource>
</local:SettingsPage>
</TabbedPage>
每個頁面都有它的 ViewModel,它在 InitializeComponent() 之后的代碼中分配給它,每個 ViewModel 從 Rest API 獲取數據
當 App 運行時,在 SplashScreen 之后所有 ViewModel 執行並獲取數據
What can I do to run each ViewModel when tab is select not before selection ?
TabbedPage 中有一個名為“OnCurrentPageChanged”的覆蓋方法,它調用選項卡更改。 我們可以在后面的代碼中使用 x:Name 屬性來訪問 xaml 的元素。
在 Xaml 中,應用 x:Name 屬性值。
<local:HomePage x:Name="Home">
<local:ExplorePage x:Name="Explore"> //use same for others pages
在后面的代碼中覆蓋下面的方法。
protected override void OnCurrentPageChanged()
{
base.OnCurrentPageChanged();
if(CurrentPage is HomePage)
{
Debug.WriteLine("Home Page");
var viewModel = Home.BindingContext as HomeViewModel;
viewModel.CallMethodToLoadData();
}else if(CurrentPage is ExplorePage)
{
Debug.WriteLine("Explore Page");
var viewModel = Explore.BindingContext as ExploreViewModel;
viewModel.CallMethodToLoadData();
}
// Same for other pages
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.