using System; using System.Collections.Generic; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Markup.Xaml.Templates; using Avalonia.Platform; using Notes.ViewModels; namespace Notes; // public class ViewLocator : IDataTemplate // { // Control? ITemplate.Build(object? param) // { // if (param == null) throw new NullReferenceException(nameof(param)); // var name = param.GetType().FullName!.Replace("ViewModel", "View"); // var type = Type.GetType(name); // // if (type != null) // { // return (Control?)Activator.CreateInstance(type); // } // else // { // return new TextBlock { Text = "1Not Found: " + name }; // } // } // // public bool Match(object? data) // { // return data is ViewModelBase; // } // } public sealed class ViewSelector : AvaloniaObject, IDataTemplate { private static readonly Dictionary controls = new Dictionary(); public ViewSelector() { } /// /// 根据ViewModel 查找view ,这里直接拿到资源文件夹的资源来构建 /// /// /// /// public Control? Build(object? param) { if (param == null) throw new NullReferenceException(nameof(param)); if (controls.TryGetValue(param, out var control)) { return control; } var name = param.GetType().FullName!.Replace("ViewModel", "View").Replace("DesignData",""); var type = Type.GetType(name); if (type != null) { var instance = (Control?)Activator.CreateInstance(type); controls[param] = instance; return instance; } else { return new TextBlock { Text = "2Not Found: " + name }; } } public bool Match(object? data) { return data is ViewModelBase; } }