在不知道集合类型的情况下将CollectionChanged添加到ObservableColleciton

时间:2013-10-23 14:53:09

标签: c# observablecollection inotifypropertychanged inotifycollectionchanged

我正在尝试将CollectionChanged事件添加到类中的任何项目。假设我有以下内容:

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事件处理程序,直到运行时

1 个答案:

答案 0 :(得分:2)

只需将其投放到INotifyCollectionChanged

var collectionChanged = propertyObject as INotifyCollectionChanged;
if (collectionChanged != null)
    collectionChanged.CollectionChanged += ...