I am trying to write a custom method for showing native dialog fragment on Android containing the MAUI ContentPage. I am using a partial class with partial method for that:
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);
}
}
}
The problem is, that the IElementToPlatform() method takes MauiContex as an argument, but I have no idea what is that, and how to recieve one?
I found only one example here: https://vladislavantonyuk.azurewebsites.net/articles/Creating-a-bottom-sheet-using-.NET-MAUI
But problem is that when I am trying to get the MauiContext from the Handler of the view (in my example the ContentPage), the Handler of that view is always null.
Do you have any relevant info about the MauiContext and how to implement it right in my solution please?
I believe the MauiContext is the object in the handler of your MAUI application contains the Context for your application. For example by which you can resolve your DI registered objects etc in your application
To get the MauiContext in ContentPage of your application you can get the object by overriding the OnHandlerChanged method which comes from Element Class.
protected override void OnHandlerChanged()
{
base.OnHandlerChanged();
var context = this.Handler.MauiContext;
}
From here https://github.com/Redth/FFImageLoading.Compat/blob/main/source/FFImageLoading.Maui/MauiExtensions.cs
public static class MauiExtensions
{
public static IMauiContext FindMauiContext(this Element element, bool fallbackToAppMauiContext = true)
{
if (element is IElement fe && fe.Handler?.MauiContext != null)
return fe.Handler.MauiContext;
foreach (var parent in element.GetParentsPath())
{
if (parent is IElement parentView && parentView.Handler?.MauiContext != null)
return parentView.Handler.MauiContext;
}
return fallbackToAppMauiContext ? Application.Current?.FindMauiContext() : default;
}
internal static IEnumerable<Element> GetParentsPath(this Element self)
{
Element current = self;
while (!IsApplicationOrNull(current.RealParent))
{
current = current.RealParent;
yield return current;
}
}
internal static bool IsApplicationOrNull(object? element) =>
element == null || element is IApplication;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With