是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(如果需要)。

如果您想了解主要表单的更改,可以直接在此注册事件。无需创建派生类。