I'm working on a WPF application. This application features a main window (main view) that is 'databind-ed' to a main view model. This main view is what instantiates the main view model.
Within this main window, sub views (i.e. usercontrols) are programmatically created. The main window features a dropdown lists that allows users to select different views. Each usercontrol view has a corresponding view model.
When a user selects a dropdown option, this triggers a new view model to be created. I then use data templating to template the view model to an instance of the associated view as shown below:
<DataTemplate DataType = "{x:Type ViewModels:MyViewModel}">
<Views:MyView />
</DataTemplate>
My question: How do I go about data binding 'MyView' to 'MyViewModel'? I'm assuming I need to add an appropriate datacontext to MyView.xaml, however, I don't know how to do this given the fact that 'MyView' is not creating an instance of 'MyViewModel'. I essentially want to databind my view to a previously existing view model. Any ideas?
EDIT: It turns out that my view automatically databinds to my view model's data template. However, I'm unsure why this just magically works. What's going on here?