如何从iOS customrenderer访问PCL渲染器中的BindableProperty

时间:2018-09-26 20:25:48

标签: c# xamarin xamarin.forms xamarin.ios

我正在尝试访问我的可绑定属性中的自定义按钮,而我尝试为其编写渲染器。首先是我的PCL渲染器:

public class BtnRenderer : Button
{

    public static readonly BindableProperty HighLightProperty = BindableProperty.Create(nameof(HighlightedBackgroundColor), typeof(Color), typeof(BtnRenderer), default(Color));

    public Color HighlightedBackgroundColor
    {
        get
        {
            return (Color)GetValue(HighLightProperty);
        }
        set
        {
            SetValue(HighLightProperty, value);
        }
    }
}

如您所见,我打算从XAML设置HighlightedBackgroundColor,但是,我不知道如何在iOS渲染器中访问它,

[assembly: ExportRenderer(typeof(BtnRenderer), typeof(BtnRendereriOS))]
namespace BluetoothExample.iOS
{
    public class BtnRendereriOS : ButtonRenderer
    {

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

            if (Control != null)
            {
                var normalBackgroundColor = Element.BackgroundColor.ToUIColor();
                var _highlightBackgroundColor = Element.HighlightedBackgroundColor.ToUIColor(); //HERE IS MY PROBLEM

            async Task NormalColorState(UIButton button)
            {
                await UIView.TransitionNotifyAsync(button, .25, UIViewAnimationOptions.TransitionCrossDissolve, () =>
                {
                    button.BackgroundColor = normalBackgroundColor;
                });
            }
            Control.TouchDown += async (object sender, EventArgs c) =>
            {
                var button = sender as UIButton;
                await UIView.TransitionNotifyAsync(button, .25, UIViewAnimationOptions.TransitionCrossDissolve, () =>
                {
                    button.BackgroundColor = _highlightBackgroundColor;
                });
            };
        }
    }
}

如何正确访问此属性?

1 个答案:

答案 0 :(得分:1)

  

//这里是我的问题

     

var _highlightBackgroundColor = Element.HighlightedBackgroundColor.ToUIColor();

直接使用Element是渲染器(VisualElementRenderer<TElement>)的基础,因此为了访问子类上的任何自定义属性,只需将其强制转换(在这种情况下为BtnRenderer):< / p>

var _highlightBackgroundColor = (Element as BtnRenderer).HighlightedBackgroundColor.ToUIColor();