2013-04-29 66 views
1

我已閱讀a very nice tutorial關於讓做的ViewModels自己的東西,而只是意見通過數據綁定切換自己與DataTemplates關聯查看和視圖模型在XAML對不重複的代碼

我成功地做它有一個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窗口資源。有沒有辦法?

回答

1

我通過使用this article發現DataTemplateManager解決了這個。

它使申報查看到視圖模型的關係是這樣的:

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

這仍然是明確的,但它降低了不得不這樣做在XAML的開銷不少。例如,考慮命名空間。

+0

要去看看! – heltonbiker 2013-04-29 19:47:17