78 lines
2.2 KiB
C#
78 lines
2.2 KiB
C#
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<object?, Control?>.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<object, Control?> controls = new Dictionary<object, Control?>();
|
|
public ViewSelector()
|
|
{
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据ViewModel 查找view ,这里直接拿到资源文件夹的资源来构建
|
|
/// </summary>
|
|
/// <param name="param"></param>
|
|
/// <returns></returns>
|
|
/// <exception cref="NullReferenceException"></exception>
|
|
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;
|
|
}
|
|
}
|