Associating View and ViewModel pairs in XAML without repetitive code

admin

Administrator
Staff member
I have read <a href="http://rachel53461.wordpress.com/2011/05/28/switching-between-viewsusercontrols-using-mvvm/" rel="nofollow">a very nice tutorial</a> about letting ViewModels do their stuff while the views just switch themselves via databinding with
Code:
DataTemplates
.

I succesfully made a window which has an ApplicationViewModel, which in turn has a hardcoded DummyViewModel as its CurrentScreen property

Code:
&lt;Window x:Class="MyProject.Aplication"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:vm="clr-namespace:MyProject.ViewModels"
        xmlns:v="clr-namespace:MyProject.Views"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="Killer Application" Height="900" Width="1440"
        WindowState="Maximized"&gt;

    &lt;!-- This view has its viewmodel as data context, which has a CurrentScreen property --&gt;
    &lt;Window.DataContext&gt;
        &lt;vm:AplicationViewModel/&gt;
    &lt;/Window.DataContext&gt;

    &lt;Window.Resources&gt;
        &lt;!-- each ViewModel will explicitly map to its current View - while this should happen EXPLICITLY, no? --&gt;
        &lt;DataTemplate DataType="{x:Type vm:DummyViewModel}"&gt;
            &lt;v:DummyView/&gt;
        &lt;/DataTemplate&gt;
        &lt;!-- Doc, are you telling me I'll have to fill this up for EVERY VIEW/VIEWMODEL? --&gt;
        &lt;DataTemplate DataType="{x:Type vm:YetAnotherViewModel}"&gt;
            &lt;v:YetAnotherView/&gt;
        &lt;/DataTemplate&gt;
    &lt;/Window.Resources&gt;

    &lt;!-- the content is bound to CurrentScreen property of the data context --&gt;
    &lt;ContentControl Content="{Binding CurrentScreen}" /&gt;
&lt;/Window&gt;

I would like to have some (very simple and direct, if possible) way to get the same result WITHOUT having to exhaustively code one
Code:
DataTemplate
Window Resource for every possible screen the window can show. Is there a way?