【发布时间】:2017-05-31 11:13:46
【问题描述】:
我想做的是让用户将项目添加到列表中。然后当他们添加一个项目时,我需要保存列表,这样当用户关闭应用程序并再次打开它时,他们创建的列表仍然存在。
现在,我可以将项目添加到我的列表中,但一旦我关闭应用程序,它们就会消失。
private static ObservableCollection<ViewModels.ZoneViewModel> Zones = new ObservableCollection<ViewModels.ZoneViewModel>();
public void PopulateListView(string image, string name, string address)
{
if (name != "" && address != "")
{
Zones.Add(new ViewModels.ZoneViewModel { Image = image, Name = name, Address = address });
Application.Current.Properties["zoneslist"] = Zones;
}
}
protected override void OnAppearing()
{
if (Application.Current.Properties.ContainsKey("zoneslist"))
{
// Put the contents of the "zoneslist" key into a variable as a string.
var savedZones = Application.Current.Properties["zoneslist"] as ObservableCollection<ViewModels.ZoneViewModel>;
// Set the listviews' itemssource to the savedzones list.
zonesList.ItemsSource = savedZones;
}
}
这是我现在使用的代码,我认为这可以保存它,但它不起作用。
编辑:所以我尝试了@Alessandro Calario 的建议,在使用 json 序列化之后,列表视图只给了我大量的空列表项(即使我只添加了一个)。但是即使应用程序关闭,也会添加并保存一个项目。至少取得了进展,但我还没有完全做到。有人知道解决办法吗?
我的代码:
public void PopulateListView(string image, string name, string address)
{
if (name != "" && address != "")
{
Zones.Add(new ViewModels.ZoneViewModel { Image = image, Name = name, Address = address });
//Serialize to json string
var json = JsonConvert.SerializeObject(Zones);
Application.Current.Properties["zoneslist"] = json;
}
}
protected override void OnAppearing()
{
if (Application.Current.Properties.ContainsKey("zoneslist"))
{
// Put the contents of the "zoneslist" key into a variable as a string.
var savedZones = Application.Current.Properties["zoneslist"] as string; //ObservableCollection<ViewModels.ZoneViewModel>
JsonConvert.DeserializeObject<ObservableCollection<ViewModels.ZoneViewModel>>(savedZones);
// Set the listviews' itemssource to the savedzones list.
zonesList.ItemsSource = savedZones;
}
}
【问题讨论】:
标签: c# listview xamarin xamarin.forms observablecollection