如何制作在 Windows 10 应用程序的所有页面中可见的全局 属性?

How to make a global property that is visible within all pages in a Windows 10 app?

我正在考虑一个代表商店的应用程序,我正在使用 GridView 查看项目,数据表示为一个 ObservableCollection。

我的XAML代码:

xmlns:data="using:ItemsStore.Models"

<GridView ItemsSource="{x:Bind ItemsList}">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="data:Item">                 
                    <StackPanel Orientation="Vertical">

                       <Image Source="{x:Bind ImageSource}"/>
                       <TextBlock  Text="{x:Bind Name}"/>
                       <TextBlock  Text="{x:Bind Disc}"/>

                    </StackPanel>
            </DataTemplate>
        </GridView.ItemTemplate>
</GridView>

主页中的 C# 代码:

public sealed partial class MainPage : Page
{
    public ObservableCollection<Item> ItemsList;

    public MainPage()
    {
        this.InitializeComponent();

        ItemsList = new ObservableCollection<Item>(); 
    }
}

我添加了一个按钮和一些输入控件来将新项目添加到 ItemsList 并且它工作得很好,但我想制作另一个包含控件和逻辑的页面以将新项目添加到列表,所以我创建了 AddNew.xaml 页面,但我无法访问 MainPage 中的 ObservableCollection 以向其添加新项目,我还尝试将 ObservableCollection 设为静态字段,我设法访问了 MainPage 中的 Collection 但我看到更新 AddNew Page 中的 Collection 后 MainPage 没有变化。

我认为问题是因为 MainPage Constructor 中的初始化语句,每次我导航到 AddNew 页面并更新 Collection 然后导航回 MainPage Constrctor 被调用并且 Collection 被重置,所以解决方案是让 ObservableCollection 成为一个 golbal 变量并在 MainPage 构造函数之外的某个地方初始化它,或者简单地在一个事件处理程序中初始化 Collection,该事件处理程序仅在应用程序启动时执行一次。

所以我的问题是: 1-有什么办法可以使应用程序中的每个页面都可见的全局 ObservableCollection 吗?如果是这样,我如何在绑定语句 (x:Bind theGlobalCollection) 或

中引用它

2- 是否有任何事件在整个应用生命周期内只被触发一次?

对于这个大问题,我感到非常抱歉,感谢您的宝贵时间。

如果我的理解是正确的,您可以简单地从构造函数中删除实例并将字段更改为:

public static ObservableCollection<Item> ItemsList = new ObservableCollection<Item>();

这样,ItemsList只被实例化一次。

基于此site, If you are wanting an ObservableCollection for all the views that you can databind in xaml, you can use Application.Current.Resources. For more information, see the reference

示例(来自来源):

public class PeopleViewModel : NotifyUIBase
{
    public ListCollectionView PeopleCollectionView {get; set;}
    private Person CurrentPerson
    {
        get { return PeopleCollectionView.CurrentItem as Person; }
        set
        {
            PeopleCollectionView.MoveCurrentTo(value);
            RaisePropertyChanged();

        }
    }
    public PeopleViewModel()
    {
        PeopleCollectionView = Application.Current.Resources["PeopleCollectionView"] as ListCollectionView;
        PeopleCollectionView.MoveCurrentToPosition(1);
    }
}