c# - 我可以保存 ObservableCollection 的内容,以便在我重新启动我的应用程序时列表仍然完好无损吗?

标签 c# listview xamarin xamarin.forms observablecollection

我想要做的是让用户将项目添加到列表中。然后,当他们添加一个项目时,我需要保存列表,这样当用户关闭应用程序并再次打开时,他们创建的列表仍然存在。

现在,我可以将项目添加到我的列表中,但一旦我关闭应用程序,它们就会消失。

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/

相关文章:

c# - 如何在 C# 中创建适用于多种类型(整数、字符串、 double 等)的泛型方法

c# - 如何在 C# 中使用 Caliburn.Micro 从 ListView 获取选定的项目和事件?

android - 数据从自定义适配器更改后刷新 ListView

user-interface - 在 Xamarin UI 测试中需要帮助

c# - 找不到类型或命名空间 IAppBuilder(缺少使用指令 pr 程序集引用)

c# - 寻找具有一对一唯一依赖关系的数据结构

c# - 如何在 Xamarin Forms 中的 "re-adding"TabbedPage 子项时禁用 BottomNavigationView 切换模式?

android - 如何更改 xamarin 表单中的导航页面后退按钮

c# - 协程第二次不工作

android - 如何同时使抽屉导航选框 ListView 中的所有 TextView ?