CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
2.98k stars 293 forks source link

MVVM Source Generator for app settings #20

Open JaiganeshKumaran opened 2 years ago

JaiganeshKumaran commented 2 years ago

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<T>(string key, T fallback);
    void SetSetting<T>(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<T>(string key, T fallback)
    {
        // TODO Implement settings read.
        return default(T);
    }

    void SetSetting<T>(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.

ghost commented 2 years ago

Hello, 'Jaiganeshkumaran! Thanks for submitting a new feature request. I've automatically added a vote 👍 reaction to help get things started. Other community members can vote to help us prioritize this feature in the future!

XAML-Knight commented 2 years ago

@Sergio0694

Arlodotexe commented 2 years ago

I'm not convinced that we need to introduce a new source generator for this. The user is able to use the existing source generators, create a view model with their settings, then hook into the PropertyChanged event to save the new value using whatever settings store they prefer.