2
votes

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?

2
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
What's the point to keep ObservableCollection<T> in the view, moreover, in the view's resources? Something going wrong with your code. - Dennis

2 Answers

2
votes

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.

0
votes

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