Pergunta

I am trying to add a CollectionChanged event to any item within a class. Assume I have the following:

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;
}

My code currently starts with Class A and looks at each item in the class that is uses INotifyPropertyChanged and assigns PropertyChanged events to each item and recursively drills down thru each sub class assigning PropertyChanged events at each level.

My issue is when I try to assign CollectionChanged events to an ObservableCollection. My code will not know the type of the item in the ObservableColleciton until runtime. I have the following code:

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);
    }
}

When I try to add the CollectionChanged event handler I get the following error:

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

How can I add the CollectionChanged event handler without knowing the class type until runtime

Foi útil?

Solução

Just cast it to INotifyCollectionChanged

var collectionChanged = propertyObject as INotifyCollectionChanged;
if (collectionChanged != null)
    collectionChanged.CollectionChanged += ...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top