CommunityToolkit / CommunityToolkit/dotnet

MVVM Source Generator for app settings

Open
#20 3 comments 1 reaction 0 assignees View on GitHub
feature request :mailbox_with_mail: mvvm-toolkit :toolbox:
Dominant language
C#
Stars
3.8k
Forks
400
PR merge metrics
No merged PRs in 30d

Description

## Describe the problem this feature would solve
Today app developers have to write a lot of boilerplate code for app settings. Consider providing a source generator and an dd an AppSettingProperty attribute to simplify settings access as an observable property.

## Describe the solution

Provide a new interface named ISettingsProvider which could be implemented by the class managing the settings. This way the app can use their own method to store and retrieve settings.
```
public interface ISettingsProvider
{
T GetSetting(string key, T fallback);
void SetSetting(string key, T value);
}
```
Then the developer could create an interface that inherits from ISettingsProvider and exposes the settings as properties with an attribute.
```
public interface IMyAppSettings : ISettingsProvider
{
[AppSettingProperty(nameof(MyAppSetting, null))]
object MyAppSetting { get; set; }
}
```
Implementation of the view model:
```
public sealed class SettingsViewModel : ObservableObject, IMyAppSettings
{
T GetSetting(string key, T fallback)
{
// TODO Implement settings read.
return default(T);
}

void SetSetting(string key, T value)
{
// TODO Implement settings write.
}
}
```
The source generator would automatically generate the code for the MyAppSetting property with the help of the GetSetting and SetSetting methods. Generated code:
```
public object MyAppSetting
{
get => GetSetting(nameof(MyAppSetting), null);
set
{
if (MyAppSetting != value)
{
OnPropertyChanging(nameof(MyAppSetting));
SetSetting(nameof(MyAppSetting), value);
OnPropertyChanged(nameof(MyAppSetting));
}
}
}
```

## Describe alternatives you've considered
None.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.