我想要做的是让用户将项目添加到列表中。然后,当他们添加一个项目时,我需要保存列表,这样当用户关闭应用程序并再次打开时,他们创建的列表仍然存在。
现在,我可以将项目添加到我的列表中,但一旦我关闭应用程序,它们就会消失。
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 序列化之后,listview 只给了我大量的空列表项(即使我只添加了一个)。但是即使应用程序关闭,也会添加并保存一个项目。进步,至少,但我还没有到那一步。有人知道解决方案吗?
我的代码:
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;
}
}
最佳答案
我认为您可以将对象列表序列化为 json 字符串并将其保存到应用程序属性
关于c# - 我可以保存 ObservableCollection 的内容,以便在我重新启动我的应用程序时列表仍然完好无损吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283275/