Handling user settings with MVVM

依然范特西╮ 提交于 2019-12-22 05:33:12

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21288604/handling-user-settings-with-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!