Trouble saving a collection of objects in Application Settings

前端 未结 2 684
难免孤独
难免孤独 2020-12-10 15:20

I\'m trying to store a collection of custom objects in the Application Settings.

With some help from this related question, here is what I currently have:



        
2条回答
  •  臣服心动
    2020-12-10 15:48

    I figured it out thanks to this question!

    As suggested in that question I added this to Settings.Designer.cs:

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

    And then all I needed was the following code:

    [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());
        }
    }
    

提交回复
热议问题