Looking for a guide to posting code that depends on property changes.
For example, I have a view model that is used to store state for application parameters
public SettingsViewModel(ISettingsRepository settings) { _settings = settings;
For each change in the settings property, we need to save this change in the repository, and affect some properties in some properties, so additional code is required.
I started just adding this logic to the setter
public ProjectCollection Projects { get { return _projects; } set { if (_projects == value) return; _projects = value; RaisePropertyChanged("Projects");
But then he switched to posting the PropertyChanged event for INotifyPropertyChanged and removed the extra code from the property setting tool
public SettingsViewModel(ISettingsRepository settings) { _settings = settings; // ... PropertyChanged += onPropertyChanged; } void onPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "Projects": _settings.SaveProjects(Projects); Startable = Projects != null && Projects.Count > 0; break; // ... } } public ProjectCollection Projects { get { return _projects; } set { if (_projects == value) return; _projects = value; RaisePropertyChanged("Projects"); } }
The presence of logic inside the setter means less code to write, less chance of an error when connecting the wrong property name (unit test should be chosen though) and will be slightly faster, although probably not significantly.
Having the logic attached to the event seems to be more suitable for searching, if the methods are properly named, it should be easier to follow the code and means that the setter doesn't do other work than setting the property, I assume this can also provide more flexibility using the above example if the requirements have changed, so that persisting changes have come from another event, for example. The Save button clicks instead of changing the property, then the code should be easier to change.
I understand that this is a subjective question, but I am new to the MVVM pattern (although, I think, can this be true for any setter logic?), So I am looking for other reasons before I agree to the approach. Thanks!