title: Using M-V-VM with WPF, how do I instantiate a Dialog View given a ViewModel?
body: <p>I'm using M-V-VM with dialog boxes.  The process I'm using for creating dialogs is as follows:</p>
  
  <ul>
  <li>A ViewModel command wishes to open a dialog.</li>
  <li>It creates the ViewModel for the dialog (we'll call it DialogViewModel).</li>
  <li>It then passes the ViewModel off to a DialogProvider to create the actual View.  This makes my dialog boxes testable, as the provider can provide either a the real view or a test view.</li>
  </ul>
  
  <p>I have this all working.  However, currently my solution for DialogProvider is to use reflection to manually find the View class to instantiate based on the name of the ViewModel, like so:</p>
  
  <pre><code>var viewModelType = viewModel.GetType();
  var dialogTypeName = Regex.Replace(viewModelType.Name, "ViewModel$", "Dialog");
  var viewType = Assembly.GetExecutingAssembly().GetType(dialogTypeName);
  if (viewType == null)
      throw new InvalidOperationException("Could not find view for given type.");
  
  var dialog = (Dialog)viewType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
  dialog.DataContext = viewModel;
  dialog.Owner = Application.Current.MainWindow;
  
  return dialog;
  </code></pre>
  
  <p>This is suboptimal, as the View must be named the same as the ViewModel, and must be in the same namespace, etc.</p>
  
  <p>Ideally I would use the DataTemplate machinery to do this.  What I would like to do is the same as using a DataTemplate for a view, and using a ContentPresenter to choose the view based on the DataTemplate's DataType attribute (see <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="nofollow noreferrer">Josh Smith's MVVM article</a>.  However, I need to do this in C# code (within the DialogProvider).  </p>
  
  <p>Is this possible?  I'm imagining things like creating a ContentPresenter in C#, settings it's DataTemplate, and then reaching it to pull the Dialog view out???</p>
  
  <p>Eric</p>