如何解决是PropertyChanged + = LinkLabel_PropertyChanged;与受保护的覆盖无效void OnPropertyChangedstring propertyName = null
在这样的Xamarin模板中。我认为有两种方法可以检查属性是否已更改。
- 添加PropertyChanged + = LinkLabel_PropertyChanged;
- 重载,呼叫基地
如果我想在一个以上的属性发生变化时做某事,那么这两种调用方法的方式之间有什么区别吗?
public class LinkLabel : Label
{
public LinkLabel()
{
PropertyChanged += LinkLabel_PropertyChanged;
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
// Check property name and do action here
}
private void LinkLabel_PropertyChanged(object sender,PropertyChangedEventArgs e)
{
// Check property name and do action here
}
}
作为参考,这是我编写的代码,我想知道这是否是一个好的解决方案:
public class LinkLabel : Label
{
public LinkLabel()
{
SetDynamicResource(Label.FontFamilyProperty,"Default-Regular");
SetDynamicResource(Label.FontSizeProperty,"LabelTextFontSize");
SetDynamicResource(Label.TextColorProperty,"LinkLabelColor");
VerticalOptions = Layoutoptions.CenterandExpand;
VerticalTextAlignment = TextAlignment.Center;
}
public static readonly BindableProperty IsImportantProperty =
BindableProperty.Create(nameof(IsImportant),typeof(bool),typeof(LinkLabel),false);
public bool IsImportant
{
get { return (bool)GetValue(IsImportantProperty); }
set { SetValue(IsImportantProperty,value); }
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == IsEnabledProperty.PropertyName ||
propertyName == IsImportantProperty.PropertyName)
{
if (this.IsEnabled) {
if (this.IsImportant)
this.SetDynamicResource(Label.TextColorProperty,"LinkLabelImportantColor");
else
this.SetDynamicResource(Label.TextColorProperty,"LinkLabelColor");
}
else
this.SetDynamicResource(Label.TextColorProperty,"LinkLabeldisabledColor");
}
}
}
解决方法
是的,不同之处在于注册PropertyChanged
事件是从外部进行的,而重写protected(!)OnPropertyChanged
方法仅是在Label的派生类内部进行的。
因此,如果您想更改标签的行为,通常只创建一个新的派生LinkLabel
类。在那里,您可以覆盖OnPropertyChanged(如果需要)。
如果您想了解主要表单的更改,可以直接在此注册事件。无需创建派生类。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。