diff --git a/Needlework.Net/ViewLocator.cs b/Needlework.Net/ViewLocator.cs index 96e0e11..a4cfcaf 100644 --- a/Needlework.Net/ViewLocator.cs +++ b/Needlework.Net/ViewLocator.cs @@ -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 _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; } }