ViewModelLocator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. #if XFORMS
  2. namespace Caliburn.Micro.Core.Xamarin.Forms
  3. #else
  4. namespace Caliburn.Micro
  5. #endif
  6. {
  7. using System;
  8. using System.Linq;
  9. using System.Text.RegularExpressions;
  10. using System.Windows;
  11. using System.Collections.Generic;
  12. using Caliburn.Micro.Core;
  13. #if WinRT
  14. using Windows.UI.Xaml;
  15. #endif
  16. #if XFORMS
  17. using UIElement = global::Xamarin.Forms.Element;
  18. #endif
  19. /// <summary>
  20. /// A strategy for determining which view model to use for a given view.
  21. /// </summary>
  22. public static class ViewModelLocator
  23. {
  24. #if ANDROID
  25. const string DefaultViewSuffix = "Activity";
  26. #elif IOS
  27. const string DefaultViewSuffix = "ViewController";
  28. #else
  29. const string DefaultViewSuffix = "View";
  30. #endif
  31. static readonly ILog Log = LogManager.GetLog(typeof(ViewModelLocator));
  32. //These fields are used for configuring the default type mappings. They can be changed using ConfigureTypeMappings().
  33. static string defaultSubNsViews;
  34. static string defaultSubNsViewModels;
  35. static bool useNameSuffixesInMappings;
  36. static string nameFormat;
  37. static string viewModelSuffix;
  38. static readonly List<string> ViewSuffixList = new List<string>();
  39. static bool includeViewSuffixInVmNames;
  40. ///<summary>
  41. /// Used to transform names.
  42. ///</summary>
  43. public static readonly NameTransformer NameTransformer = new NameTransformer();
  44. /// <summary>
  45. /// The name of the capture group used as a marker for rules that return interface types
  46. /// </summary>
  47. public static string InterfaceCaptureGroupName = "isinterface";
  48. static ViewModelLocator() {
  49. var configuration = new TypeMappingConfiguration();
  50. #if ANDROID
  51. configuration.DefaultSubNamespaceForViews = "Activities";
  52. configuration.ViewSuffixList.Add("Activity");
  53. configuration.IncludeViewSuffixInViewModelNames = false;
  54. #elif IOS
  55. configuration.DefaultSubNamespaceForViews = "ViewControllers";
  56. configuration.ViewSuffixList.Add("ViewController");
  57. configuration.IncludeViewSuffixInViewModelNames = false;
  58. #endif
  59. ConfigureTypeMappings(configuration);
  60. }
  61. /// <summary>
  62. /// Specifies how type mappings are created, including default type mappings. Calling this method will
  63. /// clear all existing name transformation rules and create new default type mappings according to the
  64. /// configuration.
  65. /// </summary>
  66. /// <param name="config">An instance of TypeMappingConfiguration that provides the settings for configuration</param>
  67. public static void ConfigureTypeMappings(TypeMappingConfiguration config)
  68. {
  69. if (String.IsNullOrEmpty(config.DefaultSubNamespaceForViews))
  70. {
  71. throw new ArgumentException("DefaultSubNamespaceForViews field cannot be blank.");
  72. }
  73. if (String.IsNullOrEmpty(config.DefaultSubNamespaceForViewModels))
  74. {
  75. throw new ArgumentException("DefaultSubNamespaceForViewModels field cannot be blank.");
  76. }
  77. if (String.IsNullOrEmpty(config.NameFormat))
  78. {
  79. throw new ArgumentException("NameFormat field cannot be blank.");
  80. }
  81. NameTransformer.Clear();
  82. ViewSuffixList.Clear();
  83. defaultSubNsViews = config.DefaultSubNamespaceForViews;
  84. defaultSubNsViewModels = config.DefaultSubNamespaceForViewModels;
  85. nameFormat = config.NameFormat;
  86. useNameSuffixesInMappings = config.UseNameSuffixesInMappings;
  87. viewModelSuffix = config.ViewModelSuffix;
  88. ViewSuffixList.AddRange(config.ViewSuffixList);
  89. includeViewSuffixInVmNames = config.IncludeViewSuffixInViewModelNames;
  90. SetAllDefaults();
  91. }
  92. private static void SetAllDefaults()
  93. {
  94. if (useNameSuffixesInMappings)
  95. {
  96. //Add support for all view suffixes
  97. ViewSuffixList.Apply(AddDefaultTypeMapping);
  98. }
  99. else
  100. {
  101. AddSubNamespaceMapping(defaultSubNsViews, defaultSubNsViewModels);
  102. }
  103. }
  104. /// <summary>
  105. /// Adds a default type mapping using the standard namespace mapping convention
  106. /// </summary>
  107. /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
  108. public static void AddDefaultTypeMapping(string viewSuffix = DefaultViewSuffix)
  109. {
  110. if (!useNameSuffixesInMappings)
  111. {
  112. return;
  113. }
  114. //Check for <Namespace>.<BaseName><ViewSuffix> construct
  115. AddNamespaceMapping(String.Empty, String.Empty, viewSuffix);
  116. //Check for <Namespace>.Views.<NameSpace>.<BaseName><ViewSuffix> construct
  117. AddSubNamespaceMapping(defaultSubNsViews, defaultSubNsViewModels, viewSuffix);
  118. }
  119. /// <summary>
  120. /// Adds a standard type mapping based on namespace RegEx replace and filter patterns
  121. /// </summary>
  122. /// <param name="nsSourceReplaceRegEx">RegEx replace pattern for source namespace</param>
  123. /// <param name="nsSourceFilterRegEx">RegEx filter pattern for source namespace</param>
  124. /// <param name="nsTargetsRegEx">Array of RegEx replace values for target namespaces</param>
  125. /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
  126. public static void AddTypeMapping(string nsSourceReplaceRegEx, string nsSourceFilterRegEx, string[] nsTargetsRegEx, string viewSuffix = DefaultViewSuffix)
  127. {
  128. var replist = new List<string>();
  129. Action<string> func;
  130. const string basegrp = "${basename}";
  131. var interfacegrp = "${" + InterfaceCaptureGroupName + "}";
  132. if (useNameSuffixesInMappings)
  133. {
  134. if (viewModelSuffix.Contains(viewSuffix) || !includeViewSuffixInVmNames)
  135. {
  136. var nameregex = String.Format(nameFormat, basegrp, viewModelSuffix);
  137. func = t =>
  138. {
  139. replist.Add(t + "I" + nameregex + interfacegrp);
  140. replist.Add(t + "I" + basegrp + interfacegrp);
  141. replist.Add(t + nameregex);
  142. replist.Add(t + basegrp);
  143. };
  144. }
  145. else
  146. {
  147. var nameregex = String.Format(nameFormat, basegrp, "${suffix}" + viewModelSuffix);
  148. func = t =>
  149. {
  150. replist.Add(t + "I" + nameregex + interfacegrp);
  151. replist.Add(t + nameregex);
  152. };
  153. }
  154. }
  155. else
  156. {
  157. func = t =>
  158. {
  159. replist.Add(t + "I" + basegrp + interfacegrp);
  160. replist.Add(t + basegrp);
  161. };
  162. }
  163. nsTargetsRegEx.ToList().Apply(t => func(t));
  164. string suffix = useNameSuffixesInMappings ? viewSuffix : String.Empty;
  165. var srcfilterregx = String.IsNullOrEmpty(nsSourceFilterRegEx)
  166. ? null
  167. : String.Concat(nsSourceFilterRegEx, String.Format(nameFormat, RegExHelper.NameRegEx, suffix), "$");
  168. var rxbase = RegExHelper.GetNameCaptureGroup("basename");
  169. var rxsuffix = RegExHelper.GetCaptureGroup("suffix", suffix);
  170. //Add a dummy capture group -- place after the "$" so it can never capture anything
  171. var rxinterface = RegExHelper.GetCaptureGroup(InterfaceCaptureGroupName, String.Empty);
  172. NameTransformer.AddRule(
  173. String.Concat(nsSourceReplaceRegEx, String.Format(nameFormat, rxbase, rxsuffix), "$", rxinterface),
  174. replist.ToArray(),
  175. srcfilterregx
  176. );
  177. }
  178. /// <summary>
  179. /// Adds a standard type mapping based on namespace RegEx replace and filter patterns
  180. /// </summary>
  181. /// <param name="nsSourceReplaceRegEx">RegEx replace pattern for source namespace</param>
  182. /// <param name="nsSourceFilterRegEx">RegEx filter pattern for source namespace</param>
  183. /// <param name="nsTargetRegEx">RegEx replace value for target namespace</param>
  184. /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
  185. public static void AddTypeMapping(string nsSourceReplaceRegEx, string nsSourceFilterRegEx, string nsTargetRegEx, string viewSuffix = DefaultViewSuffix)
  186. {
  187. AddTypeMapping(nsSourceReplaceRegEx, nsSourceFilterRegEx, new[] { nsTargetRegEx }, viewSuffix);
  188. }
  189. /// <summary>
  190. /// Adds a standard type mapping based on simple namespace mapping
  191. /// </summary>
  192. /// <param name="nsSource">Namespace of source type</param>
  193. /// <param name="nsTargets">Namespaces of target type as an array</param>
  194. /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
  195. public static void AddNamespaceMapping(string nsSource, string[] nsTargets, string viewSuffix = DefaultViewSuffix)
  196. {
  197. //need to terminate with "." in order to concatenate with type name later
  198. var nsencoded = RegExHelper.NamespaceToRegEx(nsSource + ".");
  199. //Start pattern search from beginning of string ("^")
  200. //unless original string was blank (i.e. special case to indicate "append target to source")
  201. if (!String.IsNullOrEmpty(nsSource))
  202. {
  203. nsencoded = "^" + nsencoded;
  204. }
  205. //Capture namespace as "origns" in case we need to use it in the output in the future
  206. var nsreplace = RegExHelper.GetCaptureGroup("origns", nsencoded);
  207. var nsTargetsRegEx = nsTargets.Select(t => t + ".").ToArray();
  208. AddTypeMapping(nsreplace, null, nsTargetsRegEx, viewSuffix);
  209. }
  210. /// <summary>
  211. /// Adds a standard type mapping based on simple namespace mapping
  212. /// </summary>
  213. /// <param name="nsSource">Namespace of source type</param>
  214. /// <param name="nsTarget">Namespace of target type</param>
  215. /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
  216. public static void AddNamespaceMapping(string nsSource, string nsTarget, string viewSuffix = DefaultViewSuffix)
  217. {
  218. AddNamespaceMapping(nsSource, new[] { nsTarget }, viewSuffix);
  219. }
  220. /// <summary>
  221. /// Adds a standard type mapping by substituting one subnamespace for another
  222. /// </summary>
  223. /// <param name="nsSource">Subnamespace of source type</param>
  224. /// <param name="nsTargets">Subnamespaces of target type as an array</param>
  225. /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
  226. public static void AddSubNamespaceMapping(string nsSource, string[] nsTargets, string viewSuffix = DefaultViewSuffix)
  227. {
  228. //need to terminate with "." in order to concatenate with type name later
  229. var nsencoded = RegExHelper.NamespaceToRegEx(nsSource + ".");
  230. string rxbeforetgt, rxaftersrc, rxaftertgt;
  231. string rxbeforesrc = rxbeforetgt = rxaftersrc = rxaftertgt = String.Empty;
  232. if (!String.IsNullOrEmpty(nsSource))
  233. {
  234. if (!nsSource.StartsWith("*"))
  235. {
  236. rxbeforesrc = RegExHelper.GetNamespaceCaptureGroup("nsbefore");
  237. rxbeforetgt = @"${nsbefore}";
  238. }
  239. if (!nsSource.EndsWith("*"))
  240. {
  241. rxaftersrc = RegExHelper.GetNamespaceCaptureGroup("nsafter");
  242. rxaftertgt = "${nsafter}";
  243. }
  244. }
  245. var rxmid = RegExHelper.GetCaptureGroup("subns", nsencoded);
  246. var nsreplace = String.Concat(rxbeforesrc, rxmid, rxaftersrc);
  247. var nsTargetsRegEx = nsTargets.Select(t => String.Concat(rxbeforetgt, t, ".", rxaftertgt)).ToArray();
  248. AddTypeMapping(nsreplace, null, nsTargetsRegEx, viewSuffix);
  249. }
  250. /// <summary>
  251. /// Adds a standard type mapping by substituting one subnamespace for another
  252. /// </summary>
  253. /// <param name="nsSource">Subnamespace of source type</param>
  254. /// <param name="nsTarget">Subnamespace of target type</param>
  255. /// <param name="viewSuffix">Suffix for type name. Should be "View" or synonym of "View". (Optional)</param>
  256. public static void AddSubNamespaceMapping(string nsSource, string nsTarget, string viewSuffix = DefaultViewSuffix)
  257. {
  258. AddSubNamespaceMapping(nsSource, new[] { nsTarget }, viewSuffix);
  259. }
  260. /// <summary>
  261. /// Makes a type name into an interface name.
  262. /// </summary>
  263. /// <param name = "typeName">The part.</param>
  264. /// <returns></returns>
  265. public static string MakeInterface(string typeName)
  266. {
  267. var suffix = string.Empty;
  268. if (typeName.Contains("[["))
  269. {
  270. //generic type
  271. var genericParStart = typeName.IndexOf("[[");
  272. suffix = typeName.Substring(genericParStart);
  273. typeName = typeName.Remove(genericParStart);
  274. }
  275. var index = typeName.LastIndexOf(".");
  276. return typeName.Insert(index + 1, "I") + suffix;
  277. }
  278. /// <summary>
  279. /// Transforms a View type name into all of its possible ViewModel type names. Accepts a flag
  280. /// to include or exclude interface types.
  281. /// </summary>
  282. /// <returns>Enumeration of transformed names</returns>
  283. /// <remarks>Arguments:
  284. /// typeName = The name of the View type being resolved to its companion ViewModel.
  285. /// includeInterfaces = Flag to indicate if interface types are included
  286. /// </remarks>
  287. public static Func<string, bool, IEnumerable<string>> TransformName = (typeName, includeInterfaces) =>
  288. {
  289. Func<string, string> getReplaceString;
  290. if (includeInterfaces)
  291. {
  292. getReplaceString = r => r;
  293. }
  294. else
  295. {
  296. var interfacegrpregex = @"\${" + InterfaceCaptureGroupName + @"}$";
  297. getReplaceString = r => Regex.IsMatch(r, interfacegrpregex) ? String.Empty : r;
  298. }
  299. return NameTransformer.Transform(typeName, getReplaceString).Where(n => n != String.Empty);
  300. };
  301. /// <summary>
  302. /// Determines the view model type based on the specified view type.
  303. /// </summary>
  304. /// <returns>The view model type.</returns>
  305. /// <remarks>
  306. /// Pass the view type and receive a view model type. Pass true for the second parameter to search for interfaces.
  307. /// </remarks>
  308. public static Func<Type, bool, Type> LocateTypeForViewType = (viewType, searchForInterface) =>
  309. {
  310. var typeName = viewType.FullName;
  311. var viewModelTypeList = TransformName(typeName, searchForInterface).ToList();
  312. var viewModelType = AssemblySource.FindTypeByNames(viewModelTypeList);
  313. if (viewModelType == null)
  314. {
  315. Log.Warn("View Model not found. Searched: {0}.", string.Join(", ", viewModelTypeList.ToArray()));
  316. }
  317. return viewModelType;
  318. };
  319. /// <summary>
  320. /// Locates the view model for the specified view type.
  321. /// </summary>
  322. /// <returns>The view model.</returns>
  323. /// <remarks>
  324. /// Pass the view type as a parameter and receive a view model instance.
  325. /// </remarks>
  326. public static Func<Type, object> LocateForViewType = viewType =>
  327. {
  328. var viewModelType = LocateTypeForViewType(viewType, false);
  329. if (viewModelType != null)
  330. {
  331. var viewModel = IoC.GetInstance(viewModelType, null);
  332. if (viewModel != null)
  333. {
  334. return viewModel;
  335. }
  336. }
  337. viewModelType = LocateTypeForViewType(viewType, true);
  338. return viewModelType != null
  339. ? IoC.GetInstance(viewModelType, null)
  340. : null;
  341. };
  342. /// <summary>
  343. /// Locates the view model for the specified view instance.
  344. /// </summary>
  345. /// <returns>The view model.</returns>
  346. /// <remarks>
  347. /// Pass the view instance as a parameters and receive a view model instance.
  348. /// </remarks>
  349. public static Func<object, object> LocateForView = view =>
  350. {
  351. if (view == null)
  352. {
  353. return null;
  354. }
  355. #if ANDROID || IOS
  356. return LocateForViewType(view.GetType());
  357. #elif XFORMS
  358. var frameworkElement = view as UIElement;
  359. if (frameworkElement != null && frameworkElement.BindingContext != null)
  360. {
  361. return frameworkElement.BindingContext;
  362. }
  363. return LocateForViewType(view.GetType());
  364. #else
  365. var frameworkElement = view as FrameworkElement;
  366. if (frameworkElement != null && frameworkElement.DataContext != null)
  367. {
  368. return frameworkElement.DataContext;
  369. }
  370. return LocateForViewType(view.GetType());
  371. #endif
  372. };
  373. }
  374. }