I have developed some MVVM based WPF code and am in need of some minor refactoring but prior to doing that I need to decide the best architecture.

I originally started with an application that could present several similar (but separate) representations of my data. Let's call it RecordsViewModel which had a corresponding RecordsView. As time went on, I introduced a SettingsViewModel which was passed into the constructor of the RecordsViewModel and published visibly (allowing RecordsView to use it). The SettingsViewModel is registered to so that changes are reflected in all of my views.

Now I want to split RecordsView a little because it now contains two distinct views.

The problem I have is:

the new (RecordsMainView and RecordsAlternativeView) both want to see Settings.

unlike the earlier RecordsView which is programmatically instantiated, these new views are instantiated from Xaml (default constructor).

So my options seem to be:

Walk the Tree Model upwards to find a parent with a Settings

Make Settings a DependencyProperty on the controls and make the Xaml join the Property to the instance.

1 Answer
1

I would turn your settings logic into a service (ISettingsService) and use service locator or dependency injection to get at that service from whichever view models need it.

Services are great for managing shared state, and service locator / DI makes it very easy for your VMs to get a reference to the service. Storing shared state in a VM is a bit hacky and - as you've found - doesn't really scale. A good rule of thumb might be to ask yourself whether the state in the VM exists only to support the corresponding view, or whether other components will need access to that state. If the latter, move it into a service.