我正在尝试编写一个自定义方法,用于在 Android 上显示包含 MAUI ContentPage 的本机对话框片段。我正在使用带有部分方法的部分类:
public partial void ShowCustomDialog(ContentPage contentPage)
{
if (contentPage.ToPlatform(-MauiContext-) is Android.Views.View androidView)
{
var customDialogFragment = new CustomDialogFragment();
if (customDialogFragment != null && Platform.CurrentActivity is Activity currentActivity)
{
customDialogFragment.Container.AddView(androidView);
customDialogFragment.Show(currentActivity.FragmentManager.BeginTransaction(), null);
}
}
}
问题是, IElementToPlatform() 方法将 MauiContex 作为参数,但我不知道那是什么,以及如何接收它?
我在这里只找到一个例子:https://vladislavantonyuk.azurewebsites.net/articles/Creating-a-bottom-sheet-using-.NET-MAUI
但问题是,当我尝试从视图的处理程序(在我的示例中为 ContentPage)获取 MauiContext 时,该视图的处理程序始终为 null。
您有关于 MauiContext 的相关信息以及如何在我的解决方案中正确实现它吗?
我相信 MauiContext 是 MAUI 应用程序处理程序中的对象,包含应用程序的上下文。例如,您可以在应用程序中解析您的 DI 注册对象等
要获取应用程序 ContentPage 中的 MauiContext,您可以通过重写来自 Element 类的 OnHandlerChanged 方法来获取该对象。
protected override void OnHandlerChanged()
{
base.OnHandlerChanged();
var context = this.Handler.MauiContext;
}