3

我已经阅读了一个非常好的教程,关于让 ViewModels 做他们的事情,而视图只是通过数据绑定来切换自己DataTemplates

我成功地制作了一个具有 ApplicationViewModel 的窗口,该窗口又具有硬编码的 DummyViewModel 作为其 CurrentScreen 属性

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

我希望有一些(非常简单和直接,如果可能的话)方法来获得相同的结果,而不必为DataTemplate窗口可以显示的每个可能的屏幕都详尽地编写一个窗口资源。有办法吗?

4

2 回答 2

2

我通过使用本文DataTemplateManager中找到的方法解决了这个问题。

它可以像这样声明 View-to-ViewModel 关系:

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.

于 2013-04-29T19:37:49.530 回答
2

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.

于 2013-04-29T20:03:09.950 回答