InvalidCastException when calling base.OnElementChanged(e); in custom renderer

BenVutiBenVuti ✭✭USMember ✭✭

I am trying to create a custom renderer to override how the icons in the toolbar are displayed.
I didn't get far because I get en InvalidCastException when calling base.OnElementChanged(e);

Any idea why and how to fix that ?

[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationPageRenderer))]
namespace DiapazMobile.Droid.CustomRenderers
{
    public class CustomNavigationPageRenderer : NavigationRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
        {
            base.OnElementChanged(e);

Answers

  • RyanDixonRyanDixon ✭✭✭ USMember ✭✭✭

    If that is indeed all the code you're writing then that is indeed odd.
    I'm fairly sure you don't even need to make a call to base though, correct me if I am wrong?

  • BenVutiBenVuti ✭✭ USMember ✭✭

    This all the code I wrote.
    I tried not calling the base method => I get a blank screen.

    using Android.Widget;
    using DiapazMobile.Droid.CustomRenderers;
    using Xamarin.Forms;
    using Xamarin.Forms.Platform.Android;
    
    [assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationPageRenderer))]
    namespace DiapazMobile.Droid.CustomRenderers {
        public class CustomNavigationPageRenderer : NavigationRenderer {
            protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e) {
                base.OnElementChanged(e);
    
                var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
    
            }
        }
    }
    
  • BenVutiBenVuti ✭✭ USMember ✭✭

    I traced the error to that line https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Platform.Android/Renderers/NavigationRenderer.cs#L223

    ((Platform)Element.Platform).NavAnimationInProgress = true;

    In my code e.NewElement is what becomes the Element just above if I'm not mistaken.
    I inspected the type of e.NewElement.Platform. It is a
    {Xamarin.Forms.Platform.Android.AppCompat.Platform} base: {Xamarin.Forms.BindableObject}

    I don't know what to make of all that

  • MichaelKayMichaelKay ✭✭ GBMember ✭✭

    @BenVuti did you ever resolve this? I'm having exact issue trying to implement a custom page navigation

  • MichaelKayMichaelKay ✭✭ GBMember ✭✭

    I've updated the solution in this link of a new thread i started:
    https://forums.xamarin.com/discussion/136115/custom-navigationrenderer-system-invalidcastexception

Sign In or Register to comment.