Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

c# - How can I notify property of parents that property of child is changed

I have the following code, I would like to have a way where changes in p1 are visible in access direct or propertygrid. thank you for your help

public class A
{
    int _c = 0;

    public int p1 //this is child property
    {
        get { return _c; }
        set { _c = value; } //here change, notify class B that p1 is changed
    }

}

public class B
{
    A _a = new A();

    public A p2  //this is parents property
    {
        get { return _a; }
        set { _a = value; }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.NET has a interface built in that does this for you, INotifyPropertyChanged.

What you do is you have the setter raise the event and then the parent subscribes to the event.

public class A : INotifyPropertyChanged
{
    int _c = 0;

    public int p1 //this is child property
    {
        get { return _c; }
        set 
        {
            if(_c != value)
            {
                 OnNotifyPropertyChanged("p1");
                 _c = value;
            } 
        } 
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnNotifyPropertyChanged(string propertyName)
    {
       var tmp = PropertyChanged;
       if (tmp != null)
       {
          tmp (this, new PropertyChangedEventArgs(propertyName));
       }
    }
}

public class B
{
    Public B()
    {
       _a = new A();
       _a.PropertyChanged += AChanged;
    }

    A _a;

    private AChanged(object o, PropertyChangedEventArgs e)
    {
        if(e.PropertyName == "p1")
        {
            //do your work here on change
        }
    }

    public A p2  //this is parents property
    {
        get { return _a; }
        set 
        {
           if(Object.ReferenceEquals(_a, value) == false)
           {
              _a.PropertyChanged -= AChanged; //unsubcribe from the old event
              value.PropertyChanged += AChanged; //subscribe to the new event
           }
           _a = value;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...