1

我正在尝试将 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 事件处理程序

4

1 回答 1

2

只需将其投射到INotifyCollectionChanged

var collectionChanged = propertyObject as INotifyCollectionChanged;
if (collectionChanged != null)
    collectionChanged.CollectionChanged += ...
于 2013-10-23T14:59:49.633 回答