I am trying to figure the many different ways of setting datacontext of a view to a viewmodel.
One I'm oggling at this moment goes something like this:
I have my MainWindowResource:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vw="clr-namespace:DemoStuffPartII.View"
xmlns:vm="clr-namespace:DemoStuffPartII.ViewModel">
<DataTemplate DataType="{x:Type vm:PersonViewModel}">
<vw:PersonView />
</DataTemplate>
But that's also immediately where I strand. I know that I should use a ContentControl in the View. But what is the best way to configure it? How to go about this?
Maybe this doesn't directly answer your question, but have you looked at using an MVVM framework? For example, in Caliburn.Micro you would do (very basic example):
ShellView.xaml
MyView.xaml
This is a viewmodel first approach.
There are a couple of simple ways to just bind a ViewModel to a view. As Elad mentioned you can add it in the code-behind:
or, you can specify the ViewModel as a resource in your XAML of your view:
and bind the DataContext of your LayoutRoot to that resource:
That is the way you can enable ViewSwitching navigation in your MVVM application.
The other missing bits are: in the view ->
in the ViewModel -> (pseudo code)
note however that if all u want is to connect a ViewModel to a View, you can just drop the entire DataTemplate-ContentControl thing altogether, and just do this.DataContext = new SomeViewModel(); in the codebehind.
The cleanest way I know to connect VM to Views is by using the ViewModelLocator pattern. Google ViewModelLocator.