Issue
I have this code in a template that I am using, but it's not able to work because of this message:
I understand why the message is present but I do not know how to fix this so that the label color depends on the state of the 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");
}
}
}
}
Solution
If we check the source code of class VisualElement , we will find that there is already a bindable property called IsEnabledProperty . As VisualElement is the super class of most of UI Elements . So there will be ambiguity between the two IsEnabledProperty
.
Solution 1:
The easiest way is modify the name of the bindable property like IsDisabledProperty
Solution 2:
Since there is already a IsEnabledProperty in the Label . We could set the value in xaml and handle the logic in code behind like
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");
}
}
}
Answered By - Lucas Zhang - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.