|
I'm having a hard time figuring out 'How' a view and view model gets hooked up. Where does the view datacontext actually get assigned to the instance of the view model? I know to just add the right imports and exports will do the trick, but I'm trying to figure out the 'How'. thanks. jim Follow up: Scott, How does this work if you want 2 open instances of a view model? (2 documents with different content) How does the WPF system know which instance of a viewmodel to hook to a view? jim |
|
Take a look at App.xaml.cs, specifically at the OnImportsSatisfied method:
This is from the "Host" assembly. It imports the Styles and Views, and it adds them to the application resources. From that point, WPF takes care of applying Views to ViewModels because each View is a DataTemplate where the DataType is the ViewModel type itself. Anywhere WPF sees a ViewModel in the visual tree, it automatically applies the applicable DataTemplate. 1
Scott, How does this work if you want 2 open instances of a view model? (2 documents with different content) How does the WPF system know which instance of a viewmodel to hook to a view? jim
(26 Sep '10, 08:19)
jimmy
@jimmy: It's the other way around. ViewModels are created and show up in the logical tree (either MEF instantiates them or you do) and when WPF encounters it in the logical tree, but it isn't a real WPF object, it goes hunting for a DataTemplate that has the DataType attribute set to your ViewModel's Type. If it finds one, it works like the Factory Pattern: it creates a new View object based on your DataTemplate, sets the DataContext of it to your ViewModel, and puts the instantiated View into the visual tree.
(08 Oct '10, 17:28)
Scott Whitlock ♦♦
|