I have a singleton Model and ViewModel objects and would like to programmatically create and attach WPF views to them, one at a time. Views can be created dynamically, say by selecting a menu item (somewhere). Newly created view would dispose of any old view looking at a ViewModel. Then it would make itself a current view of that ViewModel, displaying it in some WPF window serving as a container for view UserControl. I am using MEF for IoC. It is important that Model and ViewModel objects are created only once. What would be the way to accomplish this using MEF?
+2
A:
You might have a look at the ViewModel and Writer sample applications of the WPF Application Framework (WAF). They show how to switch a view using MVVM and MEF.
jbe
2010-06-26 10:58:43
Thanks, WAF looks great!
Tony
2010-06-27 00:00:39
Ok, I see now: shellViewModel.ContentView = printPreviewViewModel.View; My requirement is to keep the existing ViewModel object and change the instance of its view. I am thinking whether to derive from WAF ViewModel and add the setter for View property (currently it has only get) or, since the ViewModel object is still a rather light object, just create another instance of it.
Tony
2010-06-27 00:43:20
WAF: It's possible that more Views share the same ViewModel object. Create the ViewModel with the first View. Then retrieve the other Views (via MEF) and set the DataContext property yourself: Inside the ViewModel constructor: view2.DataContext = this;
jbe
2010-06-27 16:16:43
There are multiple views but only one is available at the time. Other views may be disposed. So the first view which is a private field in a ViewModel is a problem because it will sit there while ViewModel is alive. Wouldn't it make more sense to have a protected setter for ViewModel's View property and attach DataContext there?
Tony
2010-06-27 17:06:24
Nah, that wouldn't be a great solution for a more general case. I guess ViewModel which would be able to handle a modifiable collection of views would be more general solution. Of course, I am not asking you to change WAF to account for one special requirement. Just loudly thinking.
Tony
2010-06-27 17:17:08
Thanks for the feedback.
jbe
2010-06-28 17:54:30
A:
I use viewmodel first approach in my testapps. so i instantiate viewmodel via mef and then wpf + datatemplates do the rest. all i have to do is binding my actual viewmodel to the contentcontrol.content. you say that its important that ViewModel objects just created once. you achieve this with mef and creationPolicy.Shared or Lazy<> import. with this in mind i think ViewModel-First is the way you should go. its straightforward and you need no extra locator or wathever :)
blindmeis
2010-07-14 08:23:30