无法在“应用程序设置”中保存对象集合

我正在尝试在“应用程序设置”中存储一组自定义对象。

在这个相关问题的帮助下, 这是我目前拥有的:

// 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 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 { 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,而不是我的自定义集合(我在其他类似的问题中注意到,有时版本号有问题,这会阻止在调试时保存设置,所以我想要统治这可能是罪魁祸首。)

有任何想法吗? 我确信有一种非常简单的方法可以做到这一点,我只是想念:)。

谢谢你的帮助!

我想通了这个问题 !

正如该问题中所建议的,我将其添加到Settings.Designer.cs:

  [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public ObservableCollection AllPeople { get { return ((ObservableCollection)(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 { 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()); } } 

如果将ObservableCollection添加到您自己的代码中,但指定“Properties”命名空间,则可以在不更改settings.Designer.cs的情况下进行此更改:

 namespace MyApplication.Properties { public sealed partial class Settings { [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public ObservableCollection AllPeople { get { return ((ObservableCollection)(this["AllPeople"])); } set { this["AllPeople"] = value; } } } } 

请注意,我将Settings类的可访问性更改为 public(我可能不需要这样做)。

我在整个解决方案/答案中看到的唯一缺点是您无法再使用项目 – >属性对话框更改应用程序配置设置。 这样做会严重影响您的新设置,方法是将设置转换为字符串并修改XML标记。

因为我想使用单个系统范围的配置文件而不是用户特定的文件,所以我还将global::System.Configuration.UserScopedSettingAttribute()]更改为[global::System.Configuration.ApplicationScopedSetting()] 。 我在课堂上离开了set accesser,但我知道它实际上并没有保存。

谢谢你的回答! 它使我的代码更清洁,更易于管理。