如何根据isEnabled状态设置自定义LinkLabel的文本颜色
代码修复方案
核心调整点
原代码编译报错的根源是自定义BindableProperty和父类内置属性的命名冲突,阻断了正常编译流程,对应修复调整如下:
- 重命名自定义BindableProperty,和对接的
IsDisabled属性名称完全对齐,彻底消除和父类View内置IsEnabledProperty的重名问题。 - 给自定义BindableProperty加上
readonly修饰,适配Xamarin/MAUI的绑定系统规范,优化运行性能。 - 在状态变更回调中增加空值防护,避免类型转换失败触发的运行时空引用异常。
修复后可直接运行的代码
namespace Templates { public class LinkLabel : Label { public LinkLabel() { this.SetDynamicResource(Label.FontFamilyProperty, "Default-Regular"); this.SetDynamicResource(Label.FontSizeProperty, "LabelTextFontSize"); this.SetDynamicResource(Label.TextColorProperty, "LinkLabelColor"); VerticalTextAlignment = TextAlignment.Center; VerticalOptions = LayoutOptions.CenterAndExpand; } // 修正命名冲突,对齐自定义属性 public static readonly BindableProperty IsDisabledProperty = BindableProperty.Create( propertyName: nameof(IsDisabled), returnType: typeof(bool), declaringType: typeof(LinkLabel), defaultValue: default(bool), propertyChanged: OnIsDisabledStatusChanged); public bool IsDisabled { get => (bool)GetValue(IsDisabledProperty); set => SetValue(IsDisabledProperty, value); } private static void OnIsDisabledStatusChanged(BindableObject bindable, object oldValue, object newValue) { if (bindable is not LinkLabel label) return; label.SetDynamicResource( Label.TextColorProperty, (bool)newValue ? "LinkLabelDisabledColor" : "LinkLabelColor"); } } }
运行效果
修复后代码可正常编译执行,当IsDisabled属性值发生变化时,会自动加载对应状态的文本颜色资源,实现标签颜色随禁用状态联动切换的预期效果。
内容的提问来源于stack exchange,提问作者Alan2
相关产品推荐
相关产品推荐

