0

我有一个正在运行的 XF 应用程序,它通过 Azure API 进行大量数据库访问。到目前为止,一切都运行得很好。由于布局更改,我更改为基于 shell 的导航。我完成了整个工作,但面临一个巨大的问题。我的 app.xaml.cs 加载了很多控制器:

Public partical class App : Xamarin.Forms.Application, INotifyPropertyChanged {public static CampaignController CampaignController { get; private set; }}

在 OnStart()

CampaignController = new CampaignController(new RestService());

在公共 App() 中,我将 AppShell() 作为主页加载

MainPage = new AppShell();

这是我的 AppShell.xaml

<Shell xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:EY365OCMobileApp"
         x:Class="EY365OCMobileApp.AppShell">
<ShellContent Route="WelcomePage" ContentTemplate="{DataTemplate local:WelcomePage}">
    
</ShellContent>

WelcomePage.xaml.cs 如下所示:

protected async override void OnAppearing()
    {
        try
        {
            base.OnAppearing();
            Campaigns = await App.CampaignController.GetCampaignsAsync(364840001);
            CarouselView.ItemsSource = Campaigns;
            BindingContext = Campaigns;
        }
        catch (Exception ex)
        {
            await CreateNewBug.CreateANewBug(ex.Message,"Error in Module " + ex.Source,"\nMessage---\n{ 0}" + ex.Message + "\nInnerException---\n{ 0}" + ex.InnerException + "\nStackTrace---\n{ 0}" + ex.StackTrace + "\nTargetSite---\n{ 0}" + ex.TargetSite);
            ToastOptions toastOptions = Message.ShowMessage("An error was raised and a new bug created in our system.", "error");
            await this.DisplayToastAsync(toastOptions);
        }
    }

此行会产生错误:

            Campaigns = await App.CampaignController.GetCampaignsAsync(364840001);

你调用的对象是空的。

当我调试时,app.xaml.cs 的初始化似乎没有运行,因为它跳转到 AppShell.xaml.cs。当我将代码从 App.xaml.cs 移动到 AppShell.xaml.cs 时,它会带来同样的错误。知道如何在 Xamarin 的 shell 环境中初始化 rest-service 控制器吗?

4

1 回答 1

0

您可以在使用时延迟加载控制器。

应用程序

CampaignController _controller;
Public CampaignController controller{ 
   get
   {      
      if(_controller == null) 
      {
          _controller = new CampaignController(new RestService());
      }
      return _controller;  
   }
 }

欢迎页面

Campaigns = await (App.Current as App).controller.GetCampaignsAsync(364840001);
CarouselView.ItemsSource = Campaigns;
于 2022-02-17T02:08:02.440 回答