Browse Source

Simplify basic XAML load syntax.

Steven Kirk 10 years ago
parent
commit
e858d34b8f

+ 1 - 2
samples/XamlTestApplication/Views/MainWindow.cs

@@ -21,8 +21,7 @@
 
         private void InitializeComponent()
         {
-            var xamlLoader = new PerspexXamlLoader();
-            xamlLoader.Load(new Uri("Views/MainWindow.xaml", UriKind.Relative), this);
+            PerspexXamlLoader.Load(this);
         }
     }
 }

+ 32 - 1
src/Markup/Perspex.Xaml/PerspexXamlLoader.cs

@@ -7,9 +7,10 @@
 namespace Perspex.Xaml
 {
     using System;
+    using System.Reflection;
     using OmniXaml;
-    using Platform;
     using Perspex.Xaml.Context;
+    using Platform;
     using Splat;
 
     public class PerspexXamlLoader : XamlLoader
@@ -24,6 +25,17 @@ namespace Perspex.Xaml
         {
         }
 
+        public static void Load(object obj)
+        {
+            var loader = new PerspexXamlLoader();
+            loader.Load(obj.GetType(), obj);
+        }
+
+        public object Load(Type type, object rootInstance = null)
+        {
+            return this.Load(GetUriFor(type), rootInstance);
+        }
+
         public object Load(Uri uri, object rootInstance = null)
         {
             var assetLocator = Locator.Current.GetService<IAssetLoader>();
@@ -39,5 +51,24 @@ namespace Perspex.Xaml
                 return this.Load(stream, rootInstance);
             }
         }
+
+        private static Uri GetUriFor(Type type)
+        {
+            if (type.Namespace != null)
+            {
+                var toRemove = type.GetTypeInfo().Assembly.GetName().Name;
+                var substracted = toRemove.Length < type.Namespace.Length ? type.Namespace.Remove(0, toRemove.Length + 1) : "";
+                var replace = substracted.Replace('.', '/');
+
+                if (replace != string.Empty)
+                {
+                    replace = replace + "/";
+                }
+
+                return new Uri(replace + type.Name + ".xaml", UriKind.Relative);
+            }
+
+            return null;
+        }
     }
 }