我正在考虑一个代表商店的应用,我使用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页面中更新集合后在MainPage中。
我认为问题是因为MainPage构造函数中的初始化语句,每次我导航到AddNew页面并更新Collection然后导航回MainPage,Constrctor会被调用并且Collection被重置,所以解决方案是让ObservableCollection成为一个golbal变量并在MainPage构造函数的某个地方初始化它,或者简单地在一个事件处理程序中初始化Collection,该处理程序只在应用程序启用时执行一次。
所以我的问题是: 1-有没有办法制作一个对应用程序中每个页面都可见的全局ObservableCollection?如果是这样,我如何在绑定语句中引用它(x:绑定全局集合)或
2-是否有任何事件仅在应用有效期内被触发一次?
我很抱歉这个大问题,谢谢你的时间。
答案 0 :(得分:1)
如果我理解你是正确的,你可以简单地从构造函数中删除instatiation并将字段更改为:
public static ObservableCollection<Item> ItemsList = new ObservableCollection<Item>();
通过这种方式, ItemsList 仅实例化一次。
答案 1 :(得分:1)
根据此site,如果您想要在xaml中进行数据绑定的所有视图ObservableCollection
,则可以使用Application.Current.Resources
。有关详细信息,请参阅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);
}
}