Fix endpoints not retaining state

This commit is contained in:
BlossomiShymae
2024-08-23 20:03:18 -05:00
parent b6f713c675
commit 48751efc28

View File

@@ -1,28 +1,40 @@
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Templates; using Avalonia.Controls.Templates;
using System; using System;
using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
namespace Needlework.Net namespace Needlework.Net
{ {
public class ViewLocator : IDataTemplate public class ViewLocator : IDataTemplate
{ {
public Control? Build(object? param) private readonly Dictionary<object, Control> _controlCache = [];
{
if (param is null) return new TextBlock { Text = "data was null" };
var name = param.GetType().FullName! public Control Build(object? data)
.Replace("ViewModels", "Views") {
.Replace("ViewModel", "View"); 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); var type = Type.GetType(name);
if (type is null)
{
return new TextBlock { Text = $"No View For {name}." };
}
if (type != null) return (Control)Activator.CreateInstance(type)!; if (!_controlCache.TryGetValue(data!, out var res))
else return new TextBlock { Text = "Not Found: " + name }; {
res ??= (Control)Activator.CreateInstance(type)!;
_controlCache[data!] = res;
}
res.DataContext = data;
return res;
} }
public bool Match(object? data) public bool Match(object? data) => data is INotifyPropertyChanged;
{
return data is INotifyPropertyChanged;
}
} }
} }