2010-12-06 81 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