首页 > 解决方案 > 在自定义按钮渲染器 (Xamarin.Android) 中获取渲染类 Button(在 Xamarin.Forms 内)的实例

问题描述

我的代码中有一个简单的自定义按钮:

public class CustomButton : Button
{
    public bool State { get; set; } = false;
}

及其渲染器:

public class CustomButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
{
    public CustomButtonRenderer(Context context) : base(context) { }
    ObjectAnimator objectAnimator;

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

        if (Control != null)
        {
            var button = (Control as Android.Widget.Button);
            (Control as Android.Widget.Button).Touch += Control_Touch;

            // this don't works:
            if (Control.State) Control.SetBackgroundColor(global::Android.Graphics.Color.LightGray);                
        }
    }
 }

我想访问我班级中实例的State属性。但我不能,因为has type与我的班级完全无关。CustomButtonCustomButtonRendererControlAndroid.Support.V7.Widget.AppCompatButtonCustomButton

有什么方法可以访问CustomButton其渲染器内的渲染对象的字段?

标签: xamarinxamarin.formsxamarin.android

解决方案


Control是呈现您的CustomButton. 您正在寻找的是属性Element,它代表您的 Xamarin.Forms CustomButton

OnElementChanged其中可作为e.NewElement.

if (e.NewElement is CustomButton customButton 
    && customButton.State) 
{
    Control.SetBackgroundColor(global::Android.Graphics.Color.LightGray);  
}  

推荐阅读