[英]INotifyPropertyChanged bubbling in class hierarchy
假設我具有以下類層次結構:
public NestedClass : INotifyPropertyChanged {
string prop1;
public String Prop1 {
get { return prop1; }
set {
prop1 = value;
OnPropertyChanged("Prop1");
}
}
void OnPropertyChanged(String name) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public Class1 : INotifyPropertyChanged {
ObservableCollection<NestedClass> collection;
public Class1() {
collection = new ObservableCollection<NestedClass>();
}
public ObservableCollection<NestedClass> Collection {
get { return collection; }
set {
if (collection != null) {
collection.CollectionChanged -= childOnCollectionChanged;
}
collection = value;
if (collection != null) {
collection.CollectionChanged += childOnCollectionChanged;
}
}
}
void childOnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
((INotifyPropertyChanged)e.NewItems[0]).PropertyChanged += childOnPropertyChanged;
break;
case NotifyCollectionChangedAction.Remove:
((INotifyPropertyChanged)e.OldItems[0]).PropertyChanged -= childOnPropertyChanged;
break;
case NotifyCollectionChangedAction.Reset:
if (e.OldItems == null) { break; }
foreach (INotifyPropertyChanged itemToRemove in e.OldItems) {
itemToRemove.PropertyChanged -= childOnPropertyChanged;
}
break;
}
}
void childOnPropertyChanged(Object sender, PropertyChangedEventArgs e) {
OnPropertyChanged("nested");
}
void OnPropertyChanged(String name) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
有一個Class1
類,其中包含一些屬性和不同類的幾個集合。 所有集合的定義與NestedClass
的集合定義相同。 它們已正確綁定到UI,我在那里沒有問題。
Class1
對象和嵌套對象/集合可以在運行時創建,也可以由XML反序列化器生成。 為了正確處理反序列化的集合,分配集合時,我必須訂閱每個集合項的INotifyPropertyChanged
事件。
我的目標是處理Class1
中NestedClass
的所有項目的所有更改,以獲取有關數據已更改的信息(並將此信息傳遞給其父級)。
問題是我有多個嵌套的集合,它們通知了父類Class1
,它成功地將事件冒泡給它的父類。 但是,一個集合會通知父Class1
發生了更改,但Class1
handler
為null,因為結果Class1
不會對其父類產生冒泡事件(此處未顯示為不相關)。 我通過調試器,但無法找到問題所在。 當其他嵌套集合調用父對象的OnPropertyChanged
, handler
將不為null,並且一切正常。
編輯:僅當XML反序列化器生成Class1
和NestedClass
對象時, NestedClass
引發此問題。
我在SO上閱讀了很多類似的文章,但是其中大多數是關於視圖中無效的DataContext的,這不是我的情況(我相信)。 我還能檢查什么來找到問題的根源?
您可能要考慮切換到BindingList<T>
而不是ObserveableCollection<T>
,它具有您已經內置在childOnCollectionChanged
的邏輯。 只要確保RaiseListChangedEvents
設置為true,並且ListChanged
事件將提高args.ListChangedType == ListChangedType.ItemChanged
任何時候的一個成員提高其PropertyChanged
事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.