问题描述
我在正在使用的模板中包含此代码,但由于出现此消息而无法正常工作
我了解为什么会显示此消息,但我不知道如何解决此问题,以便标签颜色取决于isEnabled的状态。
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 BindableProperty IsEnabledProperty =
BindableProperty.Create(nameof(Isdisabled),typeof(bool),typeof(LinkLabel),default(bool),propertyChanged: IsEnabledPropertyPropertyChanged);
public bool Isdisabled
{
get { return (bool)GetValue(IsEnabledProperty); }
set { SetValue(IsEnabledProperty,value); }
}
private static void IsEnabledPropertyPropertyChanged(BindableObject bindable,object oldValue,object newValue)
{
if ((bool)newValue)
{
LinkLabel label = bindable as LinkLabel;
label.SetDynamicResource(Label.TextColorProperty,"LinkLabeldisabledColor");
}
else
{
LinkLabel label = bindable as LinkLabel;
label.SetDynamicResource(Label.TextColorProperty,"LinkLabelColor");
}
}
}
}
解决方法
如果我们检查类 VisualElement 的源代码,我们会发现已经存在一个名为 IsEnabledProperty 的可绑定属性。由于 VisualElement 是大多数UI元素的超类。因此,两个IsEnabledProperty
之间将存在歧义。
解决方案1:
最简单的方法是修改可绑定属性的名称,例如 IsDisabledProperty
解决方案2:
由于Label中已经存在 IsEnabledProperty 。我们可以在xaml中设置该值,并在后面的代码中处理逻辑,例如
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;
this.PropertyChanged += LinkLabel_PropertyChanged;
}
private void LinkLabel_PropertyChanged(object sender,PropertyChangedEventArgs e)
{
if(e.PropertyName== "IsEnabled")
{
var label = sender as LinkLabel;
var newValue = label.IsEnabled;
if ((bool)newValue)
{
this.SetDynamicResource(Label.TextColorProperty,"LinkLabelDisabledColor");
}
else
{
this.SetDynamicResource(Label.TextColorProperty,"LinkLabelColor");
}
}
}