c# – 在应用程序设置中保存对象集合

我试图在应用程序设置中存储自定义对象的集合.

this related question的一些帮助,这里是我目前拥有的:

// implementing ApplicationSettingsBase so this shows up in the Settings designer's 
// browse function
public class PeopleHolder : ApplicationSettingsBase
{
    [UserScopedSetting()]
    [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Xml)]
    public ObservableCollection<Person> People { get; set; }
}


[Serializable]
public class Person
{
    public String FirstName { get; set; }
}

public MainWindow()
{
    InitializeComponent();

    // AllPeople is always null,not persisting
    if (Properties.Settings.Default.AllPeople == null)
    {
        Properties.Settings.Default.AllPeople = new PeopleHolder()
            {
                People = new ObservableCollection<Person> 
                    { 
                        new Person() { FirstName = "bob" },new Person() { FirstName = "sue" },new Person() { FirstName = "bill" }
                    }
            };
        Properties.Settings.Default.Save();
    }
    else
    {
        MessageBox.Show(Properties.Settings.Default.AllPeople.People.Count.ToString());
    }
}

在Settings.Settings Designer中,我通过浏览器按钮添加了PeopleHolder类型的属性,并将范围设置为“User”. Save()方法似乎成功完成,没有错误消息,但每次重新启动应用程序设置都不会保留.

虽然在上面的代码中没有显示,我可以坚持Strings,只是不是我的自定义集合(我注意到在其他类似的问题,有时可能有版本号的问题,这阻止了在调试时保存设置,所以我想规则作为可能的罪魁祸首.)

有任何想法吗?我确定有一个非常简单的方法来做到这一点,我只是想念:).

谢谢你的帮助!

解决方法

我想出了 this question

正如我在这个问题中所提到的那样,我把它添加到Settings.Designer.cs中:

[global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public ObservableCollection<Person> AllPeople
    {
        get
        {
            return ((ObservableCollection<Person>)(this["AllPeople"]));
        }
        set
        {
            this["AllPeople"] = value;
        }
    }

然后我需要的是以下代码

[Serializable]
public class Person
{
    public String FirstName { get; set; }
}

public MainWindow()
{
    InitializeComponent();

    // this Now works!!
    if (Properties.Settings.Default.AllPeople == null)
    {
        Properties.Settings.Default.AllPeople = new ObservableCollection<Person> 
        { 
            new Person() { FirstName = "bob" },new Person() { FirstName = "bill" }
        };
        Properties.Settings.Default.Save();
    }
    else
    {
        MessageBox.Show(Properties.Settings.Default.AllPeople.People.Count.ToString());
    }
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...