Kubi
Kubi

Reputation: 2169

System.Collections.ObjectModel.ObservableCollection`1 Error

I'm using ObservableCollection in a portable library but I'm getting the error below. How can I solve this problem?

'System.Collections.ObjectModel.ObservableCollection1<MyClass>' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Collections.ObjectModel.ObservableCollection1' could be found (are you missing a using directive or an assembly reference?)

edited: I have this class in a portable library

Class A
{

public ObservableCollection<MyClass> MyList { get;set;}

}

and trying to use it in a WCF Service.

myA.MyList.Add(new MyClass());

Second Edit: I figured it out by putting my class having the observable collection property to a different project/library. But I'm still wondering why I got that strange error.

Another solution for this question would be a better solution structure for my projects. I'm still trying to manage it.

I am designing a Silverlight project consuming a WCF service. I have some common classes to share in both Silverlight and the WCF Service. I could not make it work by using just a portable class and share because I need some data structures to use like ObservableCollection and SortedList etc. Portable classes do not have this. Because of that reason I am having Surrogate classes in different libraries but this doesnt look good. How should I design it?

Upvotes: 1

Views: 3780

Answers (1)

newfurniturey
newfurniturey

Reputation: 38436

The error sounds like you're trying to add an item of type ObservableCollection to an existing ObservableCollection that is made of a list of MyClass objects, like:

ObservableCollection<object> miscList = new ObservableCollection<object>();
ObservableCollection<MyClass> realList = new ObservableCollection<MyClass>();
realList.Add(miscList); // miscList isn't a "MyClass" object =[

Try checking the line that's throwing the error and making sure that you're passing in the right variable (might be a typo).

UPDATE
Your code example confirms that this is the case. You define your list as ObservableCollection<MyClass>, which means that any object that is inserted into this list has to either by an instance of MyClass or inherits from MyClass.

In the following line, you're attempting to add an object of type A to the list, and A is neither MyClass nor does it inherit from MyClass:

myA.MyList.Add(new A());

To fix this, you will either need the class A to inherit MyClass (class A implements MyClass), change your list to be ObservableCollection<A> instead, or rethink the reason why you need to add a type A to that list (maybe you'll need two lists instead?).

Upvotes: 1

Related Questions