title: How to connect ViewModels to their appropriate Views dynamically?
body: <p>I have a WPF application which has a <strong>MainView.xaml</strong> Window which loads <strong>numerous page objects</strong> at runtime, loads them into <strong>ViewModels</strong>, and displays them <strong>dynamically in the menu</strong>.</p>
  
  <p>My MainViewModel has an <strong>ObservableCollection</strong> of <strong>ViewModels</strong> and I bind these each to their appropriate <strong>Views</strong> in the MainView.xaml file.</p>
  
  <p>However, is there a way to <strong>automate</strong> this so I don't have to make these manual entries each time I add a page?</p>
  
  <pre><code>&lt;Window.Resources&gt;
  
      &lt;DataTemplate DataType="{x:Type vm:PageItemManageCustomersViewModel}"&gt;
          &lt;v:PageItemManageCustomersView/&gt;
      &lt;/DataTemplate&gt;
  
      &lt;DataTemplate DataType="{x:Type vm:PageItemManageEmployeesViewModel}"&gt;
          &lt;v:PageItemManageEmployeesView/&gt;
      &lt;/DataTemplate&gt;
  
      &lt;DataTemplate DataType="{x:Type vm:PageItemReportsViewModel}"&gt;
          &lt;v:PageItemReportsView/&gt;
      &lt;/DataTemplate&gt;
  
  &lt;/Window.Resources&gt;
  </code></pre>
  
  <p>Isn't this something that a "<strong>ServiceLocator</strong>" or "<strong>Container</strong>" should be doing, hooking up the Views to the ViewModels? I've read that the above is a <strong>common way</strong> to match up the ViewModels and Views in the MVVM pattern, but it comes across as a <strong>bit static</strong> to me. Would appreciate any thoughts.</p>