11

the web site says you can in .NET 4.0

I cant seem to do it though, what assesmbly references and xmlns' do i need

the following does not work

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

<coll:ObservableCollection x:TypeArguments="x:Object">
    <MenuItem Command="ApplicationCommands.Cut"/>
    <MenuItem Command="ApplicationCommands.Copy"/>
    <MenuItem Command="ApplicationCommands.Paste"/>
</coll:ObservableCollection>
Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Aran Mulholland
  • 23,555
  • 29
  • 141
  • 228

2 Answers2

11

I just came across the same problem while working on a Windows Store App. After several problems I figured out that the easiest why to define such a collection in XAML is to simply create a subclass:

namespace my.name.space {
    public class ObservableMyObjectCollection: ObservableCollection<MyObject> {
    }
}

And then use it like so

<local:ObservableMyObjectCollection
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:my.name.space">

   <MenuItem Command="ApplicationCommands.Cut"/>
   <MenuItem Command="ApplicationCommands.Copy"/>
   <MenuItem Command="ApplicationCommands.Paste"/>

<local:ObservableMyObjectCollection>
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Andrei Herford
  • 17,570
  • 19
  • 91
  • 225
11

ObservableCollection<T> is defined in the System assembly, so your namespace should read:

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

You can find that information in MSDN at the top where it says:

Namespace: System.Collections.ObjectModel
Assembly: System (in System.dll)
XMLNS for XAML: Not mapped to an xmlns.

Note that the assembly has changed between v3.5 and v4.0. In v3.5 it was defined in the WindowsBase assembly. However, this was a drawback since you often would like to use the class without any WPF assemblies referenced. So maybe that is why they changed it.

Furthermore, you should also check this blog post, which says that the new XAML features are not completely available in VS yet!

gehho
  • 9,049
  • 3
  • 45
  • 59
  • 1
    I tried this but then I get a blue squiggly saying `The name "ObservableCollection" does not exist in the namespace "clr-namespace:System.Collections.ObjectModel;assembly=System".`. Using the `ObservableCollection` in code DOES work indeed. – rabejens May 08 '18 at 15:23