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:
RecordsMainView
and RecordsAlternativeView
) both want to see Settings.RecordsView
which is programmatically instantiated, these new views are instantiated from Xaml (default constructor).So my options seem to be:
DependencyProperty
on the controls and make the Xaml join the Property to the instance.SettingsViewModel
a Singleton.Any other, better, options? Which would you consider best?
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.
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