我正在 Xamarin 中开发一个包含 3 个选项卡的选项卡式页面( Tab1= "Home" , Tab2= "Chat" ,Tab3="Menu" )
当应用程序启动 ( ) 时,它首先将所有选项卡一起MainPage = new TabbedPage()
初始化 ( )。InitializeComponent();
我的问题是,是否有办法在按下选项卡时单独初始化每个组件?
我正在 Xamarin 中开发一个包含 3 个选项卡的选项卡式页面( Tab1= "Home" , Tab2= "Chat" ,Tab3="Menu" )
当应用程序启动 ( ) 时,它首先将所有选项卡一起MainPage = new TabbedPage()
初始化 ( )。InitializeComponent();
我的问题是,是否有办法在按下选项卡时单独初始化每个组件?
根据我的经验,大部分时间不是加载 XAML,而是“测量和布局”的组合,然后是“加载数据”(例如列表中的项目)。
这个例子展示了如何推迟“测量和布局”。它就像IsVisible="False"
在您想要延迟的任何 XAML 上进行设置一样简单。然后在需要时,设置IsVisible="True"
. 我展示了最简单的情况,即没有数据绑定。
延迟数据加载取决于您的数据。最简单的技术是以零元素开始所有列表 ( ListView
, )。CollectionView
当需要数据时,添加元素。我没有在下面显示。请参阅单击选项卡时如何加载数据。
注意:在 Android上,如果您有Visual Studio 2019 Enterprise,InitializeComponent
则可以进一步加快速度。在您的项目中,在 Project Properties / Android Options (for Configuration ) / Code Generation and Runtime 中,选中"AOT Compilation"。和“启用启动跟踪”。您可能还需要检查“使用 LLVM 优化编译器”。这些选项可能会增加应用程序包的大小。在实际设备上测试加载时间- 模拟器可能会给出关于哪种组合加载速度最快的误导性结果。(这些选项可能会给 Android 模拟器带来非常缓慢的负载。)MyProjectName.Android
"Release"
(不幸的是,我的经验是 Xamarin Forms Android 初始应用程序加载仍然明显慢于加载 Xamarin(本机)Android 应用程序(我认为这是加载 Xamarin Forms 库本身的时间)。我建议创建一个本机 Activity 以立即加载,在 XF 加载时显示一个页面。这是一个不同的主题。)
TabbedPage1.xaml:
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TabbedPage1.Views"
x:Class="TabbedPage1.TabbedPage1">
<local:StartPage Title="Start" />
<local:SlowPage Title="Slow Load" />
</TabbedPage>
TabbedPage1.xaml.cs:
using Xamarin.Forms;
namespace TabbedPage1
{
public partial class TabbedPage1 : TabbedPage
{
public TabbedPage1()
{
InitializeComponent();
}
}
}
慢页.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TabbedPage1.Views.SlowPage">
<ContentPage.Content>
<StackLayout x:Name="MyContents" IsVisible="False">
<Label Text="This text should appear after a 3 second delay."
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
慢页.xaml.cs:
using System.Threading.Tasks;
using Xamarin.Forms;
namespace TabbedPage1.Views
{
public partial class SlowPage : ContentPage
{
public SlowPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
if (!MyContents.IsVisible) {
// Simulate a page that is slow to layout or load.
await Task.Delay(3000);
MyContents.IsVisible = true;
}
}
}
}
StartPage.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TabbedPage1.Views.StartPage">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome!" FontSize="32"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
StartPage.xaml.cs:
using Xamarin.Forms;
namespace TabbedPage1.Views
{
public partial class StartPage : ContentPage
{
public StartPage()
{
InitializeComponent();
}
}
}