我已閱讀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
窗口資源。有沒有辦法?
用Nuget安裝它。已經聽說過它,但我在項目中添加框架依賴項時猶豫不決。無論如何,我想我必須忍受這個想法。 – heltonbiker 2013-04-29 20:16:13
你不會後悔的。 – devdigital 2013-04-29 20:19:02