INotifyPropertyChanged: Notify another class

前端 未结 2 1493
醉话见心
醉话见心 2021-02-09 14:57

I have a class (let\'s call it MyContainerClass)that is a container for several other classes (let\'s call them ClassA to ClassF). C

相关标签:
2条回答
  • 2021-02-09 15:23

    Okay, here is what I did after staring at Eren's solution for a while: I also implemented the INotifyPropertyChanged for the container class and registered the PropertyChanged event for each object.

    objA.PropertyChanged += updateCount;
    objB.PropertyChanged += updateCount;
    objC.PropertyChanged += updateCount;
    

    ...and so on. Then I added the following method

    private void updateCount(object sender, PropertyChangedEventArgs e)
    {
        OnPropertyChanged("Count");
    }
    

    Now I have the behavior that I want.

    0 讨论(0)
  • 2021-02-09 15:35

    Just implementing INotifyPropertyChanged is not enough for an automatic update. The MyContainerClass object needs to "subscribe" to the change notifications of the MyBaseClass objects in the other columns. One way you can handle this is by adding a method like the following to the MyContainerClass:

    void SubscribeToCount(MyBaseClass item)
    {
        item.PropertyChanged += (s,e) => 
            this.Sum += (e.NewValue - e.OldValue); 
    }
    

    And you call this method for all the objects in the other columns. (It's not clear from the question but I assume there is a wrapper class that includes instances of MyClassA-F and MyContainerClass, which you bind the datagrid to a collection of this wrapper class).

    0 讨论(0)
提交回复
热议问题