Xamarin:已过时 Forms.Context 和 AlertDialog.Builder

Xamarin: Obsolete Forms.Context and AlertDialog.Builder

我以前是这样创建的

        AlertDialog.Builder b = new AlertDialog.Builder( Forms.Context );

而且效果很好。但是 Forms.Context 现在已经过时了,所以我将其更改为

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context );

现在崩溃

Android.Content.Res.Resources+NotFoundException: Resource ID #0x0

我尝试了替代构造函数

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context, Resource.Style.Theme_AppCompat_Light );

然后崩溃

Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application

那么我在 XF2.5 中将什么上下文传递给 AlertDialog.Builder() 呢?我不想为此安装第三方库。

一种方法是像这样在 Main Activity 中创建一个静态变量

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }

    protected override void OnCreate(Bundle bundle)
    {
        ...
        global::Xamarin.Forms.Forms.Init(this, bundle);
        Instance = this;
        LoadApplication(new App());
    }
}

像这样在你的代码中引用它

AlertDialog.Builder b = new AlertDialog.Builder( MainActivity.Instance );

有关更多详细信息和实现此目的的其他方法,see David Britchs blog post