AvaloniaXamlLoaderPortableXaml.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using Avalonia.Controls;
  4. using Avalonia.Markup.Xaml.Data;
  5. using Avalonia.Markup.Xaml.PortableXaml;
  6. using Avalonia.Platform;
  7. using Portable.Xaml;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Reflection;
  12. using System.Text;
  13. namespace Avalonia.Markup.Xaml
  14. {
  15. /// <summary>
  16. /// Loads XAML for a avalonia application.
  17. /// </summary>
  18. public class AvaloniaXamlLoaderPortableXaml
  19. {
  20. private readonly AvaloniaXamlSchemaContext _context = GetContext();
  21. private static AvaloniaXamlSchemaContext GetContext()
  22. {
  23. var result = AvaloniaLocator.Current.GetService<AvaloniaXamlSchemaContext>();
  24. if (result == null)
  25. {
  26. result = AvaloniaXamlSchemaContext.Create();
  27. AvaloniaLocator.CurrentMutable
  28. .Bind<AvaloniaXamlSchemaContext>()
  29. .ToConstant(result);
  30. }
  31. return result;
  32. }
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="AvaloniaXamlLoader"/> class.
  35. /// </summary>
  36. public AvaloniaXamlLoaderPortableXaml()
  37. {
  38. }
  39. /// <summary>
  40. /// Loads the XAML into a Avalonia component.
  41. /// </summary>
  42. /// <param name="obj">The object to load the XAML into.</param>
  43. public static void Load(object obj)
  44. {
  45. Contract.Requires<ArgumentNullException>(obj != null);
  46. var loader = new AvaloniaXamlLoader();
  47. loader.Load(obj.GetType(), obj);
  48. }
  49. /// <summary>
  50. /// Loads the XAML for a type.
  51. /// </summary>
  52. /// <param name="type">The type.</param>
  53. /// <param name="rootInstance">
  54. /// The optional instance into which the XAML should be loaded.
  55. /// </param>
  56. /// <returns>The loaded object.</returns>
  57. public object Load(Type type, object rootInstance = null)
  58. {
  59. Contract.Requires<ArgumentNullException>(type != null);
  60. // HACK: Currently Visual Studio is forcing us to change the extension of xaml files
  61. // in certain situations, so we try to load .xaml and if that's not found we try .xaml.
  62. // Ideally we'd be able to use .xaml everywhere
  63. var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>();
  64. if (assetLocator == null)
  65. {
  66. throw new InvalidOperationException(
  67. "Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?");
  68. }
  69. foreach (var uri in GetUrisFor(type))
  70. {
  71. if (assetLocator.Exists(uri))
  72. {
  73. using (var stream = assetLocator.Open(uri))
  74. {
  75. var initialize = rootInstance as ISupportInitialize;
  76. initialize?.BeginInit();
  77. try
  78. {
  79. return Load(stream, rootInstance, uri);
  80. }
  81. finally
  82. {
  83. initialize?.EndInit();
  84. }
  85. }
  86. }
  87. }
  88. throw new FileNotFoundException("Unable to find view for " + type.FullName);
  89. }
  90. /// <summary>
  91. /// Loads XAML from a URI.
  92. /// </summary>
  93. /// <param name="uri">The URI of the XAML file.</param>
  94. /// <param name="baseUri">
  95. /// A base URI to use if <paramref name="uri"/> is relative.
  96. /// </param>
  97. /// <param name="rootInstance">
  98. /// The optional instance into which the XAML should be loaded.
  99. /// </param>
  100. /// <returns>The loaded object.</returns>
  101. public object Load(Uri uri, Uri baseUri = null, object rootInstance = null)
  102. {
  103. Contract.Requires<ArgumentNullException>(uri != null);
  104. var assetLocator = AvaloniaLocator.Current.GetService<IAssetLoader>();
  105. if (assetLocator == null)
  106. {
  107. throw new InvalidOperationException(
  108. "Could not create IAssetLoader : maybe Application.RegisterServices() wasn't called?");
  109. }
  110. using (var stream = assetLocator.Open(uri, baseUri))
  111. {
  112. return Load(stream, rootInstance, uri);
  113. }
  114. }
  115. /// <summary>
  116. /// Loads XAML from a string.
  117. /// </summary>
  118. /// <param name="xaml">The string containing the XAML.</param>
  119. /// <param name="rootInstance">
  120. /// The optional instance into which the XAML should be loaded.
  121. /// </param>
  122. /// <returns>The loaded object.</returns>
  123. public object Load(string xaml, object rootInstance = null)
  124. {
  125. Contract.Requires<ArgumentNullException>(xaml != null);
  126. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml)))
  127. {
  128. return Load(stream, rootInstance);
  129. }
  130. }
  131. /// <summary>
  132. /// Loads XAML from a stream.
  133. /// </summary>
  134. /// <param name="stream">The stream containing the XAML.</param>
  135. /// <param name="rootInstance">
  136. /// The optional instance into which the XAML should be loaded.
  137. /// </param>
  138. /// <param name="uri">The URI of the XAML</param>
  139. /// <returns>The loaded object.</returns>
  140. public object Load(Stream stream, object rootInstance = null, Uri uri = null)
  141. {
  142. var readerSettings = new XamlXmlReaderSettings()
  143. {
  144. BaseUri = uri,
  145. LocalAssembly = rootInstance?.GetType().GetTypeInfo().Assembly
  146. };
  147. var reader = new XamlXmlReader(stream, _context, readerSettings);
  148. object result = LoadFromReader(
  149. reader,
  150. AvaloniaXamlContext.For(readerSettings, rootInstance));
  151. var topLevel = result as TopLevel;
  152. if (topLevel != null)
  153. {
  154. DelayedBinding.ApplyBindings(topLevel);
  155. }
  156. return result;
  157. }
  158. internal static object LoadFromReader(XamlReader reader, AvaloniaXamlContext context = null)
  159. {
  160. var writer = AvaloniaXamlObjectWriter.Create(
  161. reader.SchemaContext,
  162. context);
  163. XamlServices.Transform(reader, writer);
  164. writer.ApplyAllDelayedProperties();
  165. return writer.Result;
  166. }
  167. internal static object LoadFromReader(XamlReader reader)
  168. {
  169. //return XamlServices.Load(reader);
  170. return LoadFromReader(reader, null);
  171. }
  172. /// <summary>
  173. /// Gets the URI for a type.
  174. /// </summary>
  175. /// <param name="type">The type.</param>
  176. /// <returns>The URI.</returns>
  177. private static IEnumerable<Uri> GetUrisFor(Type type)
  178. {
  179. var asm = type.GetTypeInfo().Assembly.GetName().Name;
  180. var typeName = type.FullName;
  181. yield return new Uri("resm:" + typeName + ".xaml?assembly=" + asm);
  182. yield return new Uri("resm:" + typeName + ".paml?assembly=" + asm);
  183. }
  184. }
  185. }