简体   繁体   中英

How to correctly create a Custom Renderer for StackLayout in Xamarin.Forms?

I'm trying to create a StackLayout custom renderer, and according to the documentation , the base renderer is a ViewRenderer .

So I ended up with this for iOS:

public class MyCustomStackLayout : StackLayout { }

public class MyCustomStackLayoutRenderer : ViewRenderer<MyCustomStackLayout, UIView> 
{   
        protected override void OnElementChanged(ElementChangedEventArgs<ExportableStackLayout> e)
        {
            base.OnElementChanged(e);

            // some customizations here that don't mess with BackgroundColor at all
            // removing all customizations doesn't fix the issue either.
        }
}

And I'm using it like this in my XAML:

<custom:MyCustomStackLayout BackgroundColor="Green">
</custom:MyCustomStackLayout>

Almost everything is working fine, the renderer is registered correctly and it behaves like a StackLayout , even allowing for Orientation to change, but for some reason the BackgroundColor set in my MyCustomStackLayout , is ignored, so it is always transparent.

I couldn't find exactly where in the codebase the Renderer for the original StackLayout is registered, as it is not registered in the AssemblyInfo with the other renderers, so I'm not 100% sure I'm doing the right thing here.

Is there something I'm missing that is making the BackgroundColor get ignored? Am I using the correct Renderer for StackLayout ? Does anybody know where exactly it gets registered?

Update: I do know how to implement the BackgroundColor, I'm actually interested in understanding why it doesn't work in the first place. Since I'm using the same renderer from the original StackLayout, which already implements this .

It seems a design issue of ViewRenderer . You could add the following code in the renderer .

protected override void SetBackgroundColor(Color color)
{
    base.SetBackgroundColor(color);

    if (NativeView == null)
        return;

    if (color != Color.Default)
        NativeView.BackgroundColor = color.ToUIColor();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM