about summary refs log tree commit diff
path: root/ModerationClient/ViewLocator.cs
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2024-07-29 22:45:36 +0200
committerRory& <root@rory.gay>2024-08-08 03:02:10 +0200
commit03f1669d98e1fad81bc4832900ae149ac6510ebc (patch)
tree625361563a92452297f3e2700946e51e513e78b9 /ModerationClient/ViewLocator.cs
downloadModerationClient-03f1669d98e1fad81bc4832900ae149ac6510ebc.tar.xz
Initial commit
Diffstat (limited to 'ModerationClient/ViewLocator.cs')
-rw-r--r--ModerationClient/ViewLocator.cs38
1 files changed, 38 insertions, 0 deletions
diff --git a/ModerationClient/ViewLocator.cs b/ModerationClient/ViewLocator.cs
new file mode 100644
index 0000000..3de8107
--- /dev/null
+++ b/ModerationClient/ViewLocator.cs
@@ -0,0 +1,38 @@
+using System;
+using Avalonia.Controls;
+using Avalonia.Controls.Templates;
+using Microsoft.Extensions.DependencyInjection;
+using ModerationClient.ViewModels;
+
+namespace ModerationClient;
+
+public class ViewLocator : IDataTemplate {
+    public Control? Build(object? data) {
+        try {
+            if (data is null)
+                return null;
+
+            var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
+            Console.WriteLine($"ViewLocator: Locating {name} for {data.GetType().FullName}");
+            var type = Type.GetType(name);
+            Console.WriteLine($"ViewLocator: Got {type?.FullName ?? "null"}");
+
+            if (type != null) {
+                var control = (Control)App.Current.Services.GetRequiredService(type);
+                Console.WriteLine($"ViewLocator: Created {control.GetType().FullName}");
+                control.DataContext = data;
+                return control;
+            }
+
+            return new TextBlock { Text = "Not Found: " + name };
+        }
+        catch (Exception e) {
+            Console.WriteLine($"ViewLocator: Error: {e}");
+            return new TextBlock { Text = e.ToString(), Foreground = Avalonia.Media.Brushes.Red };
+        }
+    }
+
+    public bool Match(object? data) {
+        return data is ViewModelBase;
+    }
+}
\ No newline at end of file