Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling user settings with MVVM

Currently i'm developing an WPF application with the MVVM-light framework.

On this moment i'm setting my settings as shown in the next example code in my viewmodel:

private string _property

public string Property
{
    get { return _property; }
    set
    {
        if (_property != value)
        {
            _property = value;
            Settings.Default.Property = value;
            RaisePropertyChanged("Property");
        }
    }
}

I save my settings on application exit:

protected override void OnExit(ExitEventArgs e)
{
    Settings.Default.Save();
}

Everything works as intended, but ...

Question: Is this a correct approach or is there a better way of handling settings in MVVM

like image 663
Jim Avatar asked Jan 22 '14 16:01

Jim


2 Answers

If you want to change your settings based on properties of your ViewModel, your approach would work. The only problem is that your ViewModel is tightly coupled with System.Configuration.ApplicationSettingsBase class.

I would create a Wrapper class that implements an interface (say IConfigProvider) that exposes all your settings as Properties and the Save method and inject that into your ViewModel. This way, you can pass a mock\stub when you unit test your ViewModel.

Another benefit is that if you ever decide to change the way you store your config values (say you want to store some settings in the database), you don't need to touch your ViewModels as all that job is done in your ConfigProvider class.

like image 200
Fayilt Avatar answered Oct 13 '22 09:10

Fayilt


There's a much simpler way... well the 'way' is the same, but rather than adding a setting for each property, just create a Settings class with all of your properties in... declare them as normal properties and implement the usual INotifyPropertyChanged interface. Then, and here's the difference, create just one setting for this class. That way, it's much easier to maintain.

like image 45
Sheridan Avatar answered Oct 13 '22 11:10

Sheridan