0

What is the best practice to handle application's settings contains in the external INI file between several forms?

Suppose that I have two forms -- MainForm and SettingsForm. User can open the SettingsForm from the MainForm. Now I have smth like this:

  • On Load event of the SettingsForm I read application's settings from the file and change the UI appropriately
  • On "Save" button press I write new options' values to the file
  • On the "SettingsFormClosed" event of the MainForm I read the settings from the file again

I think that the last thing is the most terrible in this case. Maybe I should use smth like SettingsSingleton or smth like this? What is the best practice to do it in C# and Windows Forms?

Thanks in advance.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • See if this help http://stackoverflow.com/questions/26369/what-is-the-best-way-to-store-user-settings-for-a-net-application – Eric Mar 27 '15 at 09:50

2 Answers2

0

You should use Observer pattern. You will need a class which represents settings file, this file is Observable. Your SettingsForm and MainForm are Observers. And SettingsForm can modify the Observable.

ZwoRmi
  • 1,093
  • 11
  • 30
0

I like to do it like this, make a Setting class for storing the values, then create a service class that is responsible for saving and supplying the settings to other objects. Service is implemented as a singleton and implements INotifyPropertyChanged. Then in your forms you just have to subscribe to ProperyChanging event from the service.

Example service code:

 public sealed class SettingsService : INotifyPropertyChanged
    {
        private static Lazy<SettingsService> instance = new Lazy<SettingsService>(() => new SettingsService());

        public static SettingsService Instance
        {
            get { return instance.Value; }
        }

        private Setting settings;
        public Setting Settings
        {
           get
           {
              var clone = settings.Clone();
              return clone;
           }
        }

        private SettingsService()
        {
           //load your settings
        }            

        public void SaveChanges(Setting settings)
        {
           //Do whatever you do to save the changes, and raise the event the   settings changed
           this.settings = settings;
           NotifyPropertyChanged();
        }


        private void NotifyPropertyChanged()
        {
            if (PropertyChanged != null)
               PropertyChanged(this, new PropertyChangedEventArgs("Settings"));
        }
        public event PropertyChangedEventHandler PropertyChanged;
}
Marko Devcic
  • 1,069
  • 2
  • 13
  • 16