How to let a parent class know about a change in its children?

后端 未结 5 1180
走了就别回头了
走了就别回头了 2021-02-09 00:28

This is an example code:

public class MyParent : INotifyPropertyChanged
{
    List MyChildren;

    public bool IsChanged
    {
        get
               


        
5条回答
  •  遇见更好的自我
    2021-02-09 01:16

    INotifyPropertyChanged has already provided the mechanism for you: the PropertyChanged event. Just have the parent add a handler to its children's PropertyChanged, and then in that handler call RaiseChanged("IsChanged");

    Also, you may want to put the INotifyPropertyChanged implementation in a base class, and have your (what appear to be) ViewModels inherit from that. Not required for this option, of course, but it will make the code a little cleaner.

    Update: In the parent object:

    // This list tracks the handlers, so you can
    // remove them if you're no longer interested in receiving notifications.
    //  It can be ommitted if you prefer.
    List> changedHandlers =
        new List>();
    
    // Call this method to add children to the parent
    public void AddChild(MyChild newChild)
    {
        // Omitted: error checking, and ensuring newChild isn't already in the list
        this.MyChildren.Add(newChild);
        EventHandler eh =
            new EventHandler(ChildChanged);
        newChild.PropertyChanged += eh;
        this.changedHandlers.Add(eh);
    }
    
    public void ChildChanged(object sender, PropertyChangedEventArgs e)
    {
        MyChild child = sender as MyChild;
        if (this.MyChildren.Contains(child))
        {
            RaiseChanged("IsChanged");
        }
    }
    

    You don't actually have to add anything to the child class, since it is already raising the correct event when it changes.

提交回复
热议问题