Reputation: 173
Let's say I have a program that has to represent some data in two different ways. If I want to accomplish this by having two different ViewModels, it seems like they should both share the same instance of the Model object. So how is this generally accomplished in MVVM with WPF?
One way I can think of is that the ViewModel constructors could take an instance of the appropriate Model and all the wiring could be done in a handler for the Application.Startup event. I don't remember seeing this done in any of the examples I've seen so far, but I may have just missed it.
So far it seems like most of the time, the examples just show the ViewModels creating instances of the Model classes themselves, which could work in some cases but doesn't seem like a good solution for my situation, since each ViewModel would be creating its own instances of Model classes. It also seems like that would eliminate the possibility of replacing the Model with a different one, which might be desired, as in the case of unit testing. I'm guessing that a dependency injection framework or IoC container would eliminate that problem though? I've only used manual dependency injection so far.
In another example, it seemed like the View created the Model objects itself and passed them to the ViewModels, which doesn't seem like such a great idea either, since the View shouldn't know anything about the Model?
Some examples don't even seem to have Model classes, just Views and ViewModels.
Are there better ways I haven't mentioned?
Additionally, should I use a dependency injection framework or IoC container? As mentioned, I haven't really used one before and I thought it might be overkill for the size of the programs I'm working on at the moment. Having not really looked into any very heavily, I may be mistaken.
Upvotes: 7
Views: 1530
Reputation: 471
You can set an Application- wide model as a singleton/ static class. Then the same instance is shared across by default.
Upvotes: 1
Reputation: 1463
You have to share the model: If you wan't to have your data in the UI updated through the INotifyPropertyChanged - this is one of the major ideas of MVVM - you should share the model (at least the relevant port for a certain ViewModel) between ViewModels.
Upvotes: -1
Reputation: 20746
The general approach is to pass a model into constructor of a view model. Probably, the examples you've looked at don't show it for the sake of simplicity. So if you have two view models that work with the same data (model), just use the same instance of the model in both.
As for dependency injection and IoC containers, as you said it is overkill for small projects, but if you project gets big it might bring you a lot of benefit.
Upvotes: 3