【问题标题】:How to access BindableProperty in PCL renderer from iOS customrenderer如何从 iOS customrenderer 访问 PCL 渲染器中的 BindableProperty
【发布时间】:2019-03-02 16:39:39
【问题描述】:

我正在尝试访问我尝试为其编写渲染器的自定义按钮的可绑定属性。首先是我的 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;
                });
            };
        }
    }
}

如何正确访问此属性?

【问题讨论】:

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


    【解决方案1】:

    //这是我的问题

    var _highlightBackgroundColor = Element.HighlightedBackgroundColor.ToUIColor();

    直接使用 Element 是您的渲染器的基础 (VisualElementRenderer&lt;TElement&gt;),因此为了访问您的子类上的任何自定义属性,只需强制转换它(在这种情况下为 BtnRenderer):

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

    【讨论】:

    • 当我释放按钮时它返回一个空引用。 (它驻留在模态视图中)
    • @JeppeChristensen 我不确定你的意思是什么...... View/VisualElement 仍然有效吗? (未处置/GC/...?)
    • 我没有在任何地方使用 dispose。我可以这样做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多