Use a DataTemplate to Associate a ViewModel to a View
By Michael Detras
We can assign a ViewModel object as the content of some control in WPF. By default, WPF will just output the string representation of the object. We can use a DataTemplate so that the content will be the appropriate View for that ViewModel.
Let's say we have the following ContentControl.
<ContentControl Content="{Binding MyViewModel}"/>
WPF will try to search for the appropriate template. If it finds nothing, then the content will be the string representation of the ViewModel. If you haven't overridden the ToString() method, then the content will be the type name. We can assign the appropriate View by using DataTemplate like below.
<DataTemplate DataType="{x:Type vm:ViewModel}">
<v:View/>
</DataTemplate>
Take note that the ViewModel will automatically be set as the DataContext of the View object.
Use a DataTemplate to Associate a ViewModel to a View (1621 Views)