3

I want to use the ObservableCollection class in Net 4.5 using the xaml.

This is how I specify the namespace in the xaml:

xmlns:coll="clr-namespace:System.Collections.ObjectModel;assembly=System"

And the collection declaration is like this:

<ic:MyControl.Resources>
    <coll:ObservableCollection x:TypeArguments="commands:Command" x:Key="CommandCollection"/>
</ic:MyControl.Resources>

I get this compile error:

The tag 'ObservableCollection' does not exist in XML namespace 'clr-namespace:System.Collections.ObjectModel;assembly=System'.

I think the assembly name may be incorrect, but a search on forums here said it is the System assembly. Can anyone tell me what's going wrong?

user3009098
  • 93
  • 1
  • 6
  • Are you checked http://stackoverflow.com/questions/2695847/wpf-xaml-create-an-observable-collectionobject-in-xaml-in-net-4-0 ? – ígor Nov 19 '13 at 14:40
  • If you are declaring this in a WPF control that will be compiled to Baml, then you are stuck with the Xaml2006 language spec, and you cannot use `x:TypeArguments` anywhere but in the root element. Xaml2009 allows it to be used anywhere, but you can only use Xaml2009 for Xaml files that you load manually at runtime. – Mike Strobel Nov 19 '13 at 16:44
  • What's the point to keep `ObservableCollection` in the view, moreover, in the view's resources? Something going wrong with your code. – Dennis Nov 20 '13 at 05:14

2 Answers2

3

From the Remarks section in the ObservableCollection documentation on MSDN:

Notes on XAML Usage

ObservableCollection can be used as a XAML object element in Windows Presentation Foundation (WPF), in versions 3.0 and 3.5. However, the usage has substantial limitations.

...

A more straightforward way to use ObservableCollection capabilities from XAML in an application is to declare your own non-generic custom collection class that derives from ObservableCollection, and constrains it to a specific type. Then map the assembly that contains this class, and reference it as an object element in your XAML.

Clemens
  • 123,504
  • 12
  • 155
  • 268
0

I agree with the answer above. However, you could go further than that and just expose your collection as a CollectionViewSource in the resource and bind to that, and then have your source collection as an ObservableCollection in your ViewModel. Details of CollectionViewSource can be found here.

CollectionViewSource

stevethethread
  • 2,524
  • 2
  • 30
  • 29