2014-04-01 33 views
0

我有一組ViewModel,每個都代表一個功能,每個ViewModel都與一個View關聯。我有一個MainWindow,我應該在其中創建視圖並顯示與之關聯的視圖模型。 o如何做到這一點?將視圖分配給MVVM中的ContentControl

MainWindow.xaml

<FlowLayoutControl> 
    <ContentControl Name="MainScreen"> 
    </ContentControl> 
</FlowLayoutControl> 

我有一個vieModel的Test1和Test2的每一個都有自己的DataTemplate。現在,我想在需要時將ContentControl設置爲其中一個視圖模型。我該怎麼做呢?

+0

你有沒有與這些特徵的ViewModels在主窗口中他們的屬性創建單獨的視圖模型? – CarbineCoder

回答

1

如果您DataTemplate在資源看起來是這樣的:

<DataTemplate DataType="{x:Type local:ViewModel}"> 
... 

當你需要使用ContentControl爲:

<ContentControl Name="MyContent">    
    <local:ViewModel /> <!-- Your ViewModel here --> 
</ContentControl> 

這意味着,DataTemplate中會明確地對所有這種類型的控件使用。

如果您DataTemplate設置x:Key

<DataTemplate x:Key="MyTemplate" DataType="{x:Type local:ViewModel}"> 
... 

當你需要使用ContentControl這樣的:

<ContentControl Name="MyContent" 
       ContentTemplate="{StaticResource MyTemplate}"> 

    <local:ViewModel /> <!-- Your ViewModel here --> 
</ContentControl> 
+0

@ harin04:我的回答對你有幫助嗎? –

+0

@ harin04:好的,你可以不理我。但下一次,我不會幫你。 –

相關問題