2013-05-31 97 views
-4

我有以下代碼,我想要在access direct或propertygrid中看到p1中的更改。 感謝你的幫助如何通知父母的財產是否改變了孩子的財產

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; } 
    } 
} 
+0

不要編輯您的問題,將其改爲全新的!發佈一個新問題! – Blorgbeard

回答

1

.NET已經爲您完成此INotifyPropertyChanged內置一個界面。

你做什麼是你有setter提高事件,然後父母訂閱事件。

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; 
     } 
    } 
} 
+0

謝謝,但我有一個問題,如果我克隆B類和PropertyChaged分配。它沒有問題嗎? –

+0

我更新了B類的例子 –

+0

非常感謝你 –

-1

首先你需要知道這不是父子關係它是構圖。如果你想繼承,我會告訴你如何通過下面的代碼實現你的目標。

public class A:B 
{ 
    int _c = 0; 

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

} 

public class B 
{ 
    public bool isChildchanged = false; 


}