UPDATE:問題已解決,請參閱my Answer。爲嵌套(子)對象訂閱INotifyPropertyChanged
我在尋找一個乾淨,優雅的解決處理INotifyPropertyChanged
事件嵌套(子)對象。示例代碼:
public class Person : INotifyPropertyChanged {
private string _firstName;
private int _age;
private Person _bestFriend;
public string FirstName {
get { return _firstName; }
set {
// Short implementation for simplicity reasons
_firstName = value;
RaisePropertyChanged("FirstName");
}
}
public int Age {
get { return _age; }
set {
// Short implementation for simplicity reasons
_age = value;
RaisePropertyChanged("Age");
}
}
public Person BestFriend {
get { return _bestFriend; }
set {
// - Unsubscribe from _bestFriend's INotifyPropertyChanged Event
// if not null
_bestFriend = value;
RaisePropertyChanged("BestFriend");
// - Subscribe to _bestFriend's INotifyPropertyChanged Event if not null
// - When _bestFriend's INotifyPropertyChanged Event is fired, i'd like
// to have the RaisePropertyChanged("BestFriend") method invoked
// - Also, I guess some kind of *weak* event handler is required
// if a Person instance i beeing destroyed
}
}
// **INotifyPropertyChanged implementation**
// Implementation of RaisePropertyChanged method
}
專注於BestFriend
屬性和它的價值設定器。現在我知道我可以手動執行此操作,執行評論中描述的所有步驟。但是這將會是很多代碼,特別是當我計劃擁有許多像這樣實現INotifyPropertyChanged
的子屬性時。當然,它們並不總是相同的類型,它們唯一共同的地方就是INotifyPropertyChanged
接口。
原因是,在我的真實場景中,我有一個複雜的「項目」(在購物車中)對象,它具有在多個圖層上嵌套對象屬性(Item有一個「License」對象,它本身可以有子對象再次),我需要得到有關「項目」的任何單一更改的通知才能重新計算價格。
你有些好的提示,甚至有些 執行幫我解決 這個?
不幸的是,我不能/允許使用PostSharp之類的構建後步驟來實現我的目標。
非常感謝你提前,
- 托馬斯
AFAIK,大多數綁定實現不希望事件以這種方式傳播。畢竟,你*還沒有*改變過BestFriend的價值。 – 2010-11-10 10:09:41