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