App-wide Observable Collection

二次信任 提交于 2019-12-11 10:12:09

问题


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

回答1:


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!




回答2:


You can either declare the collection as a static member.

Or implement the singleton pattern.

When you bind to the collection in XAML, you will need to create an accessor in your view model.

public ObservableCollection<String> Accessor
{
  get
  {
    return MyClass.oC;
  }
}



回答3:


A simple way is to declare it static and access it via the type rather than an instance:

e.g.

class SomeClass 
{
    public static bool SomeBool = false;
}

class SomeOtherClass
{
    public void SomeMethod() 
    {
        Debug.Write(SomeClass.SomeBool); // Ouput = false
    }
}

Bear in mind that this observable will be static and therefore a single instance - any modifications to it will immediately be visible to all objects accessing it - this means if some code is iterating the observable and another tries to add/remove from it - the iterator will throw an exception

If this may be the case, consider an alternative or use locking to ensure single thread access to the collection




回答4:


Well how about something like this. An everywhere accessible resource...

public class CollectionSrc
{
  public ObservableCollection<...> Col 
  { 
    get { return _col ?? (_col = new ObservableCollection<...>()); }
  }
}

In App.xaml

<ns:CollectionSrc x:Key="ColSrc" /> <!--ns .. the namespace of CollectionSrc-->

Now you can access ColSrc everywhere in the xaml code. E.g.

<ListBox ItemsSource={Binding Col, Source={StaticResource ColSrc}} />


来源:https://stackoverflow.com/questions/14937563/app-wide-observable-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!