Bejasc
Bejasc

Reputation: 960

Xamarin Custom Renderer for Button (iOS)

I've declared a custom renderer for iOS (and Android - working fine).

The custom renderer is primarily setting the background color and text color.

Setting the text color works fine for the enabled and disabled states, but I'm having trouble setting the background color for the button in different states.

I've not been able to find any documentation for Xamarin custom renderers covering this, and it is a known bug with Xamarin that I cannot get any intellisense working for iOS classes in Visual Studio, so far I've used what resources I can find on the topic.

    public class MyButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                Control.BackgroundColor= UIColor.FromRGB(235, 115, 17);

                Control.SetTitleColor(UIColor.FromRGB(255, 255, 255),UIControlState.Normal);
                Control.SetTitleColor(UIColor.FromRGB(0, 0, 0),UIControlState.Disabled);
            }
        }
    } 

I'd like to be able to change the background color to something other than what I've set - if the buttons UIControlState is Disabled.

In this image, the buttons are using the custom renderer. The top button is disabled, and the bottom is enabled. As you might guess, I'd like to make the disabled button grey.

The top button is disabled, bottom enabled.

I'm confident this must be quite straightforward, but the lack of documentation and no-intellisense issue are hindering my efforts.

Upvotes: 2

Views: 2000

Answers (1)

Sharada
Sharada

Reputation: 13601

You can override the OnElementPropertyChanged to track property changes.

protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
    base.OnElementChanged(e);

    ....

    UpdateBackground();
}

protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    base.OnElementPropertyChanged(sender, e);

    if (e.PropertyName == VisualElement.IsEnabledProperty.PropertyName)
        UpdateBackground();
}

void UpdateBackground()
{
    if (Control == null || Element == null)
        return;

    if (Element.IsEnabled)
        Control.BackgroundColor = ..;
    else
        Control.BackgroundColor = ..;
}

Upvotes: 4

Related Questions