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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With