title: Wiring up the MVVM View and ViewModel using Declarative DataContext for Design-Time and Data Template for Runtime?
body: <p>Is it possible to wire up the View and ViewModel using both a Declarative DataContext and a Data Template?  </p>
  
  <p><strong>Goal</strong>: I want to wire Views with a one ViewModel for design-time and another at run-time.  Currently, using a Declarative DataContext for a design-time VM and a Data-Template-specified VM for runtime doesn't behave as expected.</p>
  
  <p><strong>Background</strong> - There are a variety of ways to wire up a View and ViewModel including the following:</p>
  
  <p>A.) <strong><em>Declaratively specify the ViewModel DataContext within the View’s XAML</em></strong>.  This technique is useful at Design-Time using the parameter-less constructor to pass in dummy data.</p>
  
  <pre><code>&lt;UserControl.DataContext&gt;
      &lt;my: BrowseAssetsViewModel /&gt;
  &lt;/UserControl.DataContext&gt;
  </code></pre>
  
  <p>B.) <strong><em>Programmatically specify the ViewModel, View and DataContext</em></strong>.</p>
  
  <pre><code>// …Setup code
  BrowseAssetsViewModel viewModel = new BrowseAssetsViewModel(assetRegistry, domains);
  BrowseAssetsView view = new BrowseAssetsView();
  view.DataContext = viewModel;
  </code></pre>
  
  <p>When Approach B is used in combination with Approach A, at run-time WPF overrides the default DataContext specified in Approach A using the version of the ViewModel with the parameterized constructor specified in Approach B.</p>
  
  <p><em><strong>C.) Define a Data Template for the View-ViewModel association</em></strong>
  By associating a View and ViewModel in App.XAML Application.Resources, WPF can wire up the correct View based on a ViewModel’s type.</p>
  
  <pre><code>&lt;DataTemplate DataType="{x:Type vm: BrowseAssetsViewModel }"&gt;
      &lt;vw: BrowseAssetsView /&gt;
  &lt;/DataTemplate&gt;
  </code></pre>
  
  <p>If a ViewModel property were bound to a ContentPresenter control, WPF would wire-up the corresponding View (based on the ViewModel’s type) and place it within the ContentPresenter.  This is useful in the “ViewModel-first” scenario where the ViewModel is presented and WPF resolves and wires the correct View by inspecting the presented ViewModel’s type.</p>
  
  <p><strong>Problem</strong> - When using this Approach C in combination with Approach A, WPF resolves the correct View but it seems to then re-query the View, calling the declaratively specified ViewModel via the parameter-less constructor (Approach A), thus overriding the existing ViewModel property!  </p>
  
  <p><strong>Question - Is there a way to use these techniques (C and A) together without A inadvertently overwriting the C ViewModel property?</strong></p>