title: MVVM and nested view models
body: <p>I have a simple example where I'm creating a View consisting of a list box, and the list box displays a bunch of items. I'm wondering if I'm going about the creation of the View Model and Model classes correctly here. Use whatever value of correctly works in this context, I understand it's a bit subjective, but my current solution doesn't feel right. Here's a simplified version.</p>
  
  <p>The ViewModels and Models:</p>
  
  <pre class="lang-cs prettyprint-override"><code>namespace Example
  {
    public class ParentViewModel
    {
        public ParentViewModel()
        {
            // ... Create/Consume ChildViewModel * n
        }
  
        public List&lt;ChildViewModel&gt; ChildViewModels { get; set; }
    }
  
    public class ChildViewModel
    {
        public ChildViewModel()
        {
            // ... Create/Consume ChildModel
        }
  
        public ChildModel Model { get; set; }
    }
  
    public class ParentModel
    {
        public List&lt;ChildModel&gt; ChildModels { get; set; }
  
        public ParentModel()
        {
            // ... Create/Consume ChildModel * n;
        }
    }
  
    public class ChildModel
    {
        public ChildModel()
        {
            // ... Contains actual data.
        }
  
        public string Data { get; set; }
    }    
  }
  </code></pre>
  
  <p>The View:</p>
  
  <pre><code>&lt;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}"&gt;
      &lt;Window.Resources&gt;
      &lt;Example:ParentViewModel x:Key="TheViewModel" /&gt;
  &lt;/Window.Resources&gt;
  &lt;Grid&gt;
      &lt;ListBox Height="261" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="278" ItemsSource="{Binding ChildViewModels}"/&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p></p>
  
  <p>In the proper code, the listbox will use a data template to display the child view models. But as you can see I'm not sure how the to instantiate the child related objects. It feels like the ParentViewModel will have a reference to the ParentModel and create ChildViewModel objects based on the ParentModel's ChildModel objects. Now I've said that it doesn't sound so daft, but I'd be interested in your thoughts.</p>