xamarin - 在自定义按钮渲染器 (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与我的班级完全无关。CustomButton
CustomButtonRenderer
Control
Android.Support.V7.Widget.AppCompatButton
CustomButton
有什么方法可以访问CustomButton
其渲染器内的渲染对象的字段?
解决方案
Control
是呈现您的CustomButton
. 您正在寻找的是属性Element
,它代表您的 Xamarin.Forms CustomButton
。
在OnElementChanged
其中可作为e.NewElement
.
if (e.NewElement is CustomButton customButton
&& customButton.State)
{
Control.SetBackgroundColor(global::Android.Graphics.Color.LightGray);
}
推荐阅读
- network-protocols - 如何检查 Open vSwitch 中的端口状态?
- c - Esp32-(xQueueGenericReceive)- 断言失败
- github - 如何从 Git 忽略特定文件夹中的任何更改
- python - 在詹金斯中获取控制台输出作为参数或变量
- flutter - 发送有关新文档创建的推送通知
- vue.js - ./node_modules/bootstrap-vue/src/index.scss 中的 BootstrapVue 未知字错误
- ajax - 我可以使用 ajax/php 更快地发出 wikidata 请求吗?
- angularjs - 如何使用 Laravel 在 Angular JS 中创建多步表单
- android - 如何减少 Android 中的 APK 大小?
- android - 如何在移动设备上调整网站的ui