【发布时间】:2016-02-07 22:06:14
【问题描述】:
我正在考虑一个代表商店的应用程序,我正在使用 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>
MainPage 中的 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 成为一个全局变量并在 MainPage 构造函数之外的某个地方对其进行初始化,或者只是在应用启动时仅执行一次的事件处理程序中初始化 Collection。
所以我的问题是: 1-有没有办法让应用程序中的每个页面都可以看到全局 ObservableCollection ?如果是这样,我如何在绑定语句中引用它(x:Bind theGlobalCollection)或
2- 是否有任何事件在应用生命周期内仅触发一次?
对于这个大问题,我感到非常抱歉,感谢您的宝贵时间。
【问题讨论】:
标签: c# xaml windows-10 uwp windows-10-universal