2010-12-06 80 views
18

我有一個簡單的例子,我創建一個包含列表框的視圖,列表框顯示一堆項目。我想知道是否在這裏正確地創建View Model和Model類。在這種情況下使用任何正確工作的價值,我知道這有點主觀,但我目前的解決方案並不正確。這是一個簡化版本。MVVM和嵌套視圖模型

的的ViewModels和模型:

namespace Example 
{ 
    public class ParentViewModel 
    { 
     public ParentViewModel() 
     { 
      // ... Create/Consume ChildViewModel * n 
     } 

     public List<ChildViewModel> ChildViewModels { get; set; } 
    } 

    public class ChildViewModel 
    { 
     public ChildViewModel() 
     { 
      // ... Create/Consume ChildModel 
     } 

     public ChildModel Model { get; set; } 
    } 

    public class ParentModel 
    { 
     public List<ChildModel> ChildModels { get; set; } 

     public ParentModel() 
     { 
      // ... Create/Consume ChildModel * n; 
     } 
    } 

    public class ChildModel 
    { 
     public ChildModel() 
     { 
      // ... Contains actual data. 
     } 

     public string Data { get; set; } 
    }  
} 

的觀點:

<Window x:Class="Example.View" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Example="clr-namespace:Example" Title="View" Height="300" Width="300" 
    DataContext="{StaticResource TheViewModel}"> 
    <Window.Resources> 
    <Example:ParentViewModel x:Key="TheViewModel" /> 
</Window.Resources> 
<Grid> 
    <ListBox Height="261" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="278" ItemsSource="{Binding ChildViewModels}"/> 
</Grid> 

在正確的代碼,列表框將使用數據模板來顯示子視圖模型。但正如你所看到的,我不確定如何實例化與子對象相關的對象。感覺像ParentViewModel將有一個對ParentModel的引用,並基於ParentModel的ChildModel對象創建ChildViewModel對象。現在我已經說過這聽起來不那麼愚蠢,但我會對你的想法感興趣。

回答

15

你是在正確的軌道上。

父模型自然包含子模型的列表,例如,有多個訂單的客戶。

ParentViewModel由第三方創建並加載時,它通過ParentModel。然後ParentViewModel會:

  1. 分配ParentModel局部變量
  2. 通過將 ChildModelChildViewModel構造
  3. 每個那些ChildViewModels添加到列表
創建每個 ChildModel一個 ChildViewModel

順便說一下,你想

public List<ChildViewModel> ChildViewModels { get; set; } 

public ObservableCollection<ChildViewModel> ChildViewModels { get; set; } 
+0

1爲的ObservableCollection。 – 2010-12-06 13:27:15