我正在将我在Xamarin.iOS中编写的应用程序重写为Xamarin.Forms,我曾经在DidEnterBackground和WillEnterForeground上执行了一些代码。现在我找不到Xamarin.Forms中的等效方法。我在我的App类中尝试过mainPage.Appearing和mainPage.Disappearing,但它们似乎与我想要实现的不同。任何人吗?
答案 0 :(得分:4)
我不相信Xamarin.Forms的功能。您可以安装Xamarin.Forms.Labs(可在NuGet上使用)并从XFormsApplicationDelegate继承您的应用程序委托。您可以在GitHub源上查看sample app delegate。
public partial class AppDelegate : XFormsApplicationDelegate
{
然后,您需要使用DI容器注册IXFormsApp接口:
private void SetIoc()
{
var resolverContainer = new SimpleContainer();
var app = new XFormsAppiOS();
app.Init(this);
resolverContainer.Register<IXFormsApp>(app);
Resolver.SetResolver(resolverContainer.GetResolver());
}
一旦在DI容器上注册了应用程序,您就可以通过解析器在共享/ PCL代码上使用它。您将订阅Resumed和Suspended事件。 Sample here.
var app = Resolver.Resolve<IXFormsApp>();
if (app == null)
{
return;
}
app.Closing += (o, e) => Debug.WriteLine("Application Closing");
app.Error += (o, e) => Debug.WriteLine("Application Error");
app.Initialize += (o, e) => Debug.WriteLine("Application Initialized");
app.Resumed += (o, e) => Debug.WriteLine("Application Resumed");
app.Rotation += (o, e) => Debug.WriteLine("Application Rotated");
app.Startup += (o, e) => Debug.WriteLine("Application Startup");
app.Suspended += (o, e) => Debug.WriteLine("Application Suspended");