heltonbiker
heltonbiker

Reputation: 27585

Associating View and ViewModel pairs in XAML without repetitive code

I have read a very nice tutorial about letting ViewModels do their stuff while the views just switch themselves via databinding with DataTemplates.

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

<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">

    <!-- This view has its viewmodel as data context, which has a CurrentScreen property -->
    <Window.DataContext>
        <vm:AplicationViewModel/>
    </Window.DataContext>

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

    <!-- the content is bound to CurrentScreen property of the data context -->
    <ContentControl Content="{Binding CurrentScreen}" />
</Window>

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

Upvotes: 3

Views: 2894

Answers (2)

devdigital
devdigital

Reputation: 34349

If you're doing MVVM, then you should be using an MVVM framework. For example, Caliburn.Micro will do view location and automatic binding based on conventions.

Upvotes: 2

Fede
Fede

Reputation: 44038

I resolved this by using the DataTemplateManager found in this article.

It enables to declare the View-to-ViewModel relation like this:

manager.RegisterDataTemplate<ViewModelA, ViewA>();
manager.RegisterDataTemplate<ViewModelB, ViewB>();

This is still explicit, but it reduces a LOT of overhead of having to do it in XAML. Think about namespaces for instance.

Upvotes: 2

Related Questions