Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save huoxudong125/ff4922cdad403f2f89b5346bc3ca89c8 to your computer and use it in GitHub Desktop.
Save huoxudong125/ff4922cdad403f2f89b5346bc3ca89c8 to your computer and use it in GitHub Desktop.
A generic wrapper for AppSettings values to allow them to be used in Windows Forms bindings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Reflection;
using System.ComponentModel;
/// <summary>
/// Wraps a value in appSettings for use with bindings,
/// will read from and write to appSettings.
/// Example of use:
/// textBox.DataBindings.Add(
/// "Text", // Data member to bind to
/// new SettingsValueBindingWrapper<string>(settingName), // Type and name of setting in appConfig
/// "Value",
/// false,
/// DataSourceUpdateMode.OnPropertyChanged);
/// </summary>
class AppSettingsValueBindingWrapper<T> : INotifyPropertyChanged
{
#region Private fields
private TypeConverter converter;
private Configuration config;
private string settingName;
#endregion
#region Lifecycle
public SettingsValueBindingWrapper(string settingName)
{
converter = TypeDescriptor.GetConverter(typeof(T));
config = ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);
this.settingName = settingName;
}
#endregion
#region Properties
public T Value
{
get
{
return (T)converter.ConvertFromString(config.AppSettings.Settings[settingName].Value);
}
set
{
ModifySettingValue(settingName, value);
}
}
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Private methods
private void ModifySettingValue(string settingName, T newValue)
{
config.AppSettings.Settings[settingName].Value = converter.ConvertToString(newValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs(settingName));
}
// Have to reopen the config after changing it
config = ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment