使用MVVM处理用户设置 [英] Handling user settings with MVVM
问题描述
当前,我正在使用MVVM-light
框架开发WPF
应用程序.
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 ...
问题:这是正确的方法还是有更好的方法来处理MVVM中的设置
Question: Is this a correct approach or is there a better way of handling settings in MVVM
推荐答案
如果要基于ViewModel
的属性更改设置,则可以使用该方法.唯一的问题是您的ViewModel
与System.Configuration.ApplicationSettingsBase
类紧密结合.
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.
我将创建一个Wrapper类,该类实现一个接口(例如 IConfigProvider ),该接口将所有设置公开为Properties和Save方法,并将其注入到ViewModel
中.这样,当您对ViewModel
进行单元测试时,您可以通过模拟\存根.
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
.
另一个好处是,如果您决定更改配置值的存储方式(例如,您想在数据库中存储一些设置),则无需触摸ViewModels
,因为所有工作都已完成在您的ConfigProvider
课堂中.
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.
这篇关于使用MVVM处理用户设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!