Not Singleton ViewModel and still synchronizing
I would like to have two (o开发者_Go百科r even more) different WPF windows (using MVVM!) but bound to the same type ViewModel
. But the main thing is that I need those two windows to have synchronized content, both are displaying the same observable collection.
Synchronizing would be easy with Singleton Pattern design of that ViewModel
but I was told that singleton ViewModels is a terrible design.
So, What is the best strategy where and when to assign datacontext and where to create ViewModels
to solve this scenario?
ViewModels can have properties exposing other ViewModels. The View for the outer ViewModel can have a ContentControl
bound to the inner ViewModel.
In this way, you can have separate ViewModel instances that are bound the the Windows themselves, and only the part that needs to be the same between those 2 Views should be in the shared inner ViewModel. So your inner ViewModel could expose data like a collection, while the separate ViewModels bound to their respective Windows can keep track of the selected item in the collection.
But I think normally people make sure the data itself (Models) are shared, if at all, rather than ViewModels, as ViewModels tend to encapsulate behavior in addition to data, and you have to be very careful about an action on one Window doing the exact same thing as the same action on a different Window. It carries a high risk of confusing the user due to unexpected side-effects.
As for how to make this easier to do, if you're not using an MVVM framework, you might try one. MVVM Light as a good one to start with if you haven't used one, though I personally use Caliburn Micro. MVVM Light has a template for a ViewModelLocator you might use to control ViewModel creation/reference, and you basically edit/add to the ViewModelLocator yourself. Both play well with IOC containers, which would give you finer control over ViewModel creation.
For example, any time a new Window for the outer ViewModel is opened, you've registered that ViewModel with the IOC container such that a new instance is created each time. And when the outer ViewModel needs a instance of the inner ViewModel, you've registered a single instance in the container that gets returned for that, rather than a new instance being created each time. (Whether this happens by using the IOC container as a Service Locator or as actual Dependency Injection is up to you.)
This article may be of interest, as well.
Please comment if you need anything clarified in regards to your original question, as it was a little broad. There are simply a lot of ways to do what you want to do.
精彩评论