使用 INotifyPropertyChanged 继承

Inheritance with INotifyPropertyChanged

我想知道是否有人知道如何解决以下问题...我有一个基础 class 需要更新它的 modifiedDateTime 属性 当派生 class 属性 已更改。

BaseObject.cs

public class BaseObject
{
    private DateTime? _modifiedDateTime;

    public DateTime? modifiedDateTime 
    {
        get { return _modifiedDateTime ; }
        set { _modifiedDateTime  = value; }
    }

    public BaseObject
    {
        _modifiedDateTime = DateTime.Now.ToUniversalTime();
    }

    public void Update(object sender, PropertyChangedEventArgs e)
    {
        _modifiedDateTime = DateTime.Now.ToUniversalTime();
    }
}

ExampleClass1.cs

public class ExampleClass1: BaseObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int _data;

    public int data
    {
        get { return _data; }
        set 
        {
            _data = value;
            PropertyChanged?.Invoke(this,  new PropertyChangedEventArgs("data"));               
        }
    }

    public ExampleClass1()
    {
        PropertyChanged += base.Update;
    }
}

前面的示例按预期工作。

但是,如果派生 class 包含另一个 class 的对象。例如:

ExampleClass2.cs

public class ExampleClass2: BaseObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int _data;

    private ExampleClass1 _objClass1;

    public int data
    {
        get { return _data; }
        set 
        {
            _data = value;
            PropertyChanged?.Invoke(this,  new PropertyChangedEventArgs("data"));               
        }
    }

    public ExampleClass1 objClass1
    {
        get { return _objClass1; }
        set 
        {
            _objClass1 = value;
            PropertyChanged?.Invoke(this,  new PropertyChangedEventArgs("objClass1"));               
        }
    }

    public ExampleClass2()
    {
        PropertyChanged += base.Update;
    }
}

当我更改 objClass1data 属性 时,基 ExampleClass2modifiedDateTime 属性 继承 class BaseObject 未更新。

我该如何解决这个问题?

当您设置 objClass1 的值时,也订阅其 属性 更改的事件

public ExampleClass1 objClass1 {
    get { return _objClass1; }
    set {
        //in case one already existed. unsubscribe from event
        if(_objClass1 != null) _objClass1.PropertyChanged -= base.Update
        _objClass1 = value;
        //subscribe to event
        if(_objClass1 != null) _objClass1.PropertyChanged += base.Update
        PropertyChanged?.Invoke(this,  new PropertyChangedEventArgs("objClass1"));               
    }
}