1

我正在嘗試將CollectionChanged事件添加到類中的任何項目。假設我有以下幾點:將CollectionChanged添加到ObservableColleciton而不知道集合類型

public class A 
{ 
    string OneString; 
    string TwoString; 
    ObservableCollection<B> CollectionOfB; 
} 

public class B 
{ 
    string ThreeString; 
    string FourString; 
    string FiveString; 
    ObservableCollection<C> CollectionOfC; 
} 

public class C 
{ 
    string SixString; 
    string SevenString; 
} 

我的代碼目前開始與A級和是使用INotifyPropertyChanged的和分配的PropertyChanged事件的每個項目和遞歸下鑽通的每個子類指定類查看每個項目的PropertyChanged事件在每個級別。

我的問題是當我嘗試將CollectionChanged事件分配給ObservableCollection。我的代碼直到運行時纔會知道ObservableColleciton中的項目類型。我有以下代碼:

protected virtual void RegisterSubPropertyForChangeTracking(INotifyPropertyChanged propertyObject) 
{ 
    propertyObject.PropertyChanged += new PropertyChangedEventHandler(propertyObject_PropertyChanged); 

    // if this propertyObject is also an ObservableCollection then add a CollectionChanged event handler 
    if (propertyObject.GetType().GetGenericTypeDefinition().Equals(typeof(ObservableCollection<>))) 
    { 
     ((ObservableCollection<object>)propertyObject).CollectionChanged += 
      new NotifyCollectionChangedEventHandler(propertyObject_CollectionChanged); 
    } 
} 

當我嘗試添加CollectionChanged事件處理程序,我得到以下錯誤:

{"Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[SOC.Model.Code3]' to type 'System.Collections.ObjectModel.ObservableCollection`1[System.Object]'."} 

我如何可以添加CollectionChanged事件處理程序不知道類的類型,直到運行時

回答

2

只需將它轉換爲INotifyCollectionChanged

var collectionChanged = propertyObject as INotifyCollectionChanged; 
if (collectionChanged != null) 
    collectionChanged.CollectionChanged += ... 
相關問題