Language: C#
ViewModelLocator.cs
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: }
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

