reflectionmaui.net-9.0native-aot

Access private property with internal type AOT save


i tried to resolve aot warnings in my .Net maui app. I have a mapping like this:

    Microsoft.Maui.Handlers.TabbedViewHandler.Mapper.AppendToMapping("TabbedPageCenterLabels", (handler, view) => {
        var tabbedPageManager = typeof(TabbedPage).GetField("_tabbedPageManager", BindingFlags.NonPublic | BindingFlags.Instance)?.
            GetValue(handler.VirtualView);

        var navView = (BottomNavigationView?)tabbedPageManager.GetType()
            .GetProperty("BottomNavigationView", BindingFlags.NonPublic | BindingFlags.Instance)
            ?.GetValue(tabbedPageManager);
    });

The GetProperty("BottomNavigationView",..) method generate a IL2075 warning. My problem is, that the "_tabbedPageManager" field in TabbedPage is type of TabbedPageManager. TabbedPageManager is a internal class. From this internal class i need the "BottomNavigationView" private property.
How can i get the BottomNavigationView property in internal class TabbedPageManager?

Most samples i found using this: typeof(MyClass).GetProperty("..."). But can't use typeof(TabbedPageManager).GetProperty("...") because TabbedPageManager is not accessable (internal). Also

[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "get_BottomNavigationView")]
extern static BottomNavigationView InstanceGetter(TabbedPageManager @this);

is not working. For the same reason.

Thank you


Solution

  • Depending on @Szymon Roziewski answer, this works for me:

    protected override void ConnectHandler(View nativeView) {
        base.ConnectHandler(nativeView);
        nativeView.Post(() => {
            var parent = nativeView?.Parent;
            while(parent != null) {
                if(parent is ViewGroup parentGroup) {
                    bottomNavigationView = FindBottomNavigationView(parentGroup);
                    if(bottomNavigationView != null) {
                        //Do something
                        break;
                    }
                }
                parent = parent.Parent;
            }
        });
    }
    

    The bottomNavigationView is in the parent layout and inserted by MAUI after the handler is connected.