Trouble saving a collection of objects in Application Settings

前端 未结 2 686
难免孤独
难免孤独 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 16:09

    If you add the ObservableCollection to your own code, but specify the "Properties" namespace, you can make this change without altering the 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;
                }
            }
        }
    }
    

    Please note, I changed the accessibility of the Settings class to be public. (I probably didn't need to do that).

    The only downside I saw in this whole solution/answer is that you are no longer able to make changes to the application configuration settings using the Project -> Properties dialog. Doing so will seriously mess up your new settings by converting you setting to a string and mangling your XML tags.

    Because I wanted to use a single system-wide configuration file instead of a user-specific file, I also changed the global::System.Configuration.UserScopedSettingAttribute()] to [global::System.Configuration.ApplicationScopedSetting()]. I left the set accesser in the class, but I know that it doesn't actually save.

    Thanks for the answer! It makes my code a whole lot cleaner and easier to manage.

提交回复
热议问题