This is helpful when you need a bare-bones configuration file in an INI file format. The PreferenceService can be used in Dependency Injection (DI) or a regular class instance. The current setup always saves after setting a parameter
This has been tested on Windows, Linux, and Mac.
Usecases include AOT complation and minimilistic configuration system.
The follow example makes use of Prism Library's SetProperty(...) to automatically save to the settings file using the property's name as the key. This is a generic example and should be taylored for your own use cases.
public class SettingsViewModel
{
private string _networkHost1 = string.Empty;
private ZoneType _zoneTypeSelected;
public SettingsViewModel(IPreferenceService prefs)
{
// NOTE! The 'key' value MUST be the same as the property name
// so that [CallerMemberName] can work when saving.
_networkHost1 = _prefs.NetworkHost1;
// Loading an enum sample
_zoneTypeSelected = (ZoneType)_prefs.GetValue(Section.Settings, "ZoneTypeSelected", (int)ZoneType.Unknown);
}
public string SlotType { get => _slotType; set => SaveProperty(ref _slotType, value); }
// NOTE: When saving, the INI's Key is pulled from the Property's name
// And we must save the value as INT
public ZoneType ZoneTypeSelected { get => _zoneTypeSelected; set => SavePropertyInt(ref _zoneTypeSelected, value); }
public IEnumerable<ZoneType> ZoneTypes => Enum.GetValues<ZoneType>().Cast<ZoneType>();
private void SaveProperty<T>(ref T storage, T value, [CallerMemberName] string? propertyName = null)
{
// WARNING:
// The property names above are STRONGLY typed to the PreferenceService's property names
// We're cheating below assuming "propertyName" == the service's property name.
// SO, be sure to name them the exact same so .NET's reflection can do it's magic.
SetProperty(ref storage, value);
// The '!' denotes that WE KNOW it's not NULL
Debug.WriteLine($"Saving: [{propertyName}] '{storage}' = '{value}'");
_prefs.SetValue(Section.Settings, propertyName!, value?.ToString()!);
}
private void SavePropertyInt<T>(ref T storage, T value, [CallerMemberName] string? propertyName = null)
{
// WARNING:
// The property names above are STRONGLY typed to the PreferenceService's property names
// We're cheating below assuming "propertyName" == the service's property name.
// SO, be sure to name them the exact same so .NET's reflection can do it's magic.
SetProperty(ref storage, value);
// The '!' denotes that WE KNOW it's not NULL
Debug.WriteLine($"Saving: [{propertyName}] '{storage}' = '{value}'");
int valueInt = Convert.ToInt32(value);
_prefs.SetValue(Section.Settings, propertyName!, valueInt);
}
}