-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViewLocator.cs
39 lines (32 loc) · 1.01 KB
/
ViewLocator.cs
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
39
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace YouBook;
public class ViewLocator : IDataTemplate
{
private readonly Dictionary<object, Control> _controlCache = new();
public Control Build(object? data)
{
var fullName = data?.GetType().FullName;
if (fullName is null)
{
return new TextBlock { Text = "Data is null or has no name." };
}
var name = fullName.Replace("ViewModel", "View");
var type = Type.GetType(name);
if (type is null)
{
return new TextBlock { Text = $"No View For {name}." };
}
if (!_controlCache.TryGetValue(data!, out var res))
{
res ??= (Control)Activator.CreateInstance(type)!;
_controlCache[data!] = res;
}
res.DataContext = data;
return res;
}
public bool Match(object? data) => data is INotifyPropertyChanged;
}