1

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?

4

1 回答 1

1

该错误听起来像是您正在尝试将类型的项目添加到由对象列表组成ObservableCollection的现有项目中,例如:ObservableCollectionMyClass

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

尝试检查引发错误的行并确保您传递了正确的变量(可能是错字)。

更新
您的代码示例证实了这种情况。您将列表定义为ObservableCollection<MyClass>,这意味着插入此列表的任何对象必须通过 的实例MyClass或继承 MyClass

在以下行中,您尝试将类型的对象添加A到列表中,并且A它既不是MyClass也不是继承自MyClass

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

要解决此问题,您将需要类A继承MyClass( class A implements MyClass),将列表更改为ObservableCollection<A>,或者重新考虑需要A向该列表添加类型的原因(也许您需要两个列表来代替?)。

于 2012-10-02T02:33:01.353 回答