about summary refs log tree commit diff
path: root/ModerationClient/ViewLocator.cs
blob: 3de8107565af6a8c6320607018cfbbda3048545b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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;
    }
}