Search code examples
c#.netxamlwindows-8microsoft-metro

App-wide Observable Collection


If I put an Observable Collection inside a separate .cs (class) file and use it in my MainPage.xaml, how can I make it so that all the data stored inside that same Observable Collection is accessible from within a different XAML page at a later time?

E.g.

MyClass.cs:
public ObservableCollection<String> oC = new ObservableCollection<String>();

MainPage.xaml.cs:
// add to observable collection

SecondPage.xaml.cs:
// access and use data stored in ObservableCollection

Solution

  • I think you just want this:

    MyClass.cs:
    public static ObservableCollection<String> oC = new ObservableCollection<String>();
    
    MainPage.xaml.cs:
    // add to observable collection
    
    SecondPage.xaml.cs:
    // access and use data stored in ObservableCollection
    

    Once the oC is static, you can reference it again and again from any class / page.

    If however you want to bind to it (since you cannot bind to fields OR to static properties in Windows 8 apps) you need to have that XAML page reference your static property in a simple property:

    SecondPage.xaml.cs:
    public static ObservableCollection<String> oC { get { return MyClass.oC; } }
    

    I hope this makes sense!