/// <summary> /// Handles the PropertyChanged event of the Settings class instance. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param> private void Settings_PropertyChanged(object sender, PropertyChangedEventArgs e) { // NOTE:: Do use this attribute, if no notification is required from a property: [DoNotNotify] try // just try from the beginning.. { PropertyInfo propertyInfo = // first get the property info for the property.. GetType().GetProperty(e.PropertyName, BindingFlags.Instance | BindingFlags.Public); // get the property value.. object value = propertyInfo?.GetValue(this); // get the setting attribute value of the property.. if (propertyInfo != null) { SettingAttribute settingAttribute = (SettingAttribute)propertyInfo.GetCustomAttribute(typeof(SettingAttribute)); if (value != null && settingAttribute != null) { conflib[settingAttribute.SettingName] = value.ToString(); } } } catch { // ignored.. } }
/// <summary> /// Initializes a new instance of the <see cref="Settings"/> class. /// </summary> public Settings() { if (conflib == null) // don't initialize if already initialized.. { conflib = new Conflib { AutoCreateSettings = true // set it to auto-create SQLite database tables.. }; // create a new instance of the Conflib class.. } // get all public instance properties of this class.. PropertyInfo[] propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); // loop through the properties.. for (int i = 0; i < propertyInfos.Length; i++) { try // avoid crashes.. { // get the SettingAttribute class instance of the property.. SettingAttribute settingAttribute = (SettingAttribute)propertyInfos[i].GetCustomAttribute(typeof(SettingAttribute)); // get the default value for the property.. object currentValue = propertyInfos[i].GetValue(this); // set the value for the property using the default value as a // fall-back value.. if (currentValue == null) { continue; } propertyInfos[i].SetValue(this, Convert.ChangeType(conflib[settingAttribute.SettingName, currentValue.ToString()], settingAttribute.SettingType)); } catch { // ignored.. } } // subscribe the event handler.. PropertyChanged += Settings_PropertyChanged; }