我已阅读a very nice tutorial关于让ViewModel执行他们的工作,而视图只是通过数据绑定DataTemplates
切换自己。
我成功创建了一个具有ApplicationViewModel的窗口,而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
窗口资源。有办法吗?
答案 0 :(得分:2)
我使用this article中的DataTemplateManager
解决了此问题。
它可以声明View-to-ViewModel关系,如下所示:
manager.RegisterDataTemplate<ViewModelA, ViewA>();
manager.RegisterDataTemplate<ViewModelB, ViewB>();
这仍然是明确的,但它减少了在XAML中执行此操作所需的大量开销。例如,考虑名称空间。
答案 1 :(得分:2)