CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

ViewModelLocator.cs

1105 Views
Copy Code Show/Hide Line Numbers
   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Diagnostics;
   4:  using System.Linq;
   5:  using System.Reflection;
   6:  using System.Windows.Data;
   7:   
   8:  namespace VMLocatorSample.ViewModels
   9:  {
  10:      public class ViewModelLocator
  11:      {
  12:          private static Dictionary<Type, Object> ViewModels;
  13:   
  14:          static ViewModelLocator()
  15:          {
  16:              ViewModels = new Dictionary<Type, Object>();
  17:          }
  18:   
  19:          public object ViewModel
  20:          {
  21:              get { return GetViewModel(); }
  22:          }
  23:   
  24:          private object GetViewModel()
  25:          {
  26:              Type viewType = GetViewType();
  27:              object viewModel = null;
  28:   
  29:              if (!ViewModels.TryGetValue(viewType, out viewModel))
  30:              {
  31:                  var viewModelType = Type.GetType(viewType.FullName.Replace("View", "ViewModel"));
  32:                  viewModel = Activator.CreateInstance(viewModelType);
  33:                  ViewModels[viewType] = viewModel;
  34:              }
  35:   
  36:              return viewModel;
  37:          }
  38:   
  39:          private Type GetViewType()
  40:          {
  41:              var stack = new StackTrace();
  42:   
  43:              return stack.GetFrames()
  44:                  .Select(f => f.GetMethod())
  45:                  .Where(m => m.Name == "InitializeComponent")
  46:                  .Select(m => m.DeclaringType)
  47:                  .FirstOrDefault();
  48:          }
  49:      }
  50:  }
by Bobby Diaz
  March 31, 2010 @ 8:44am
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate