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

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top