Search code examples
xamarin.formsxamarin.android

Xamarin.Forms - getting Control from ImageButtonRenderer


I am trying to create a subclass of ImageButton called TintedImageButton that (surprise) can tint the image. I am following the basic structure of some TintedImage code I have found.

TintedImageButton has three renderers for iOS, Android and UWP.

The Android version of TintedImageButtonRenderer isn't working because it can't access the "Control" property of its superclass, ImageButtonRenderer. The Control should be the native widget.

I have been unable to locate the class documentation for ImageButtonRenderer but decompiling seems to indicate that the Control property has been made private for Android, but not for iOS. Does anyone know why this might be? How can I get the native widget so I can modify it?


Solution

  • The ImageButtonRenderer inherits from AppCompatImageButton, so the class myImageButtonRender itself is a native control which is a subclass of AppCompatImageButton.

    [assembly: ExportRenderer(typeof(TintedImageButton), typeof(myImageButtonRender))]
    namespace App261.Droid
    {
        class myImageButtonRender : ImageButtonRenderer
        {
            public myImageButtonRender(Context context) : base(context)
            {
    
            }
    
    
            protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ImageButton> e)
            {
                base.OnElementChanged(e);
    
    
                this.SetImageResource(Resource.Drawable.sample);
    
                AppCompatImageButton imagV = this as AppCompatImageButton;
    
            }
        }
    }