using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Cowain.Base.Helpers;
using Cowain.Base.ViewModels;
using Cowain.TestProject.ViewModels;
using System;
using System.Text.RegularExpressions;
namespace Cowain.TestProject
{
///
/// 视图定位器,根据视图模型定位视图
///
public class ViewLocator : IDataTemplate
{
public Control? Build(object? param)
{
if (param is null)
return null;
var dataType = param.GetType();
var name = dataType.FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
//var type = Type.GetType(name);
// 完全限定名
var type = Type.GetType($"{name}, {GetAssemblyName(dataType)}");
if (type != null)
{
return (Control)Activator.CreateInstance(type)!;
}
return new TextBlock { Text = "Not Found: " + name };
}
public bool Match(object? data)
{
return data is ViewModelBase || data is PageViewModelBase;
}
///
/// 获取程序集名称
///
///
///
private string GetAssemblyName(Type type)
{
// 类型的完整名称
string? input = type.AssemblyQualifiedName;
if (input is null)
{
return string.Empty;
}
// 正则表达式匹配两个逗号之间的内容
var match = Regex.Match(input, ",(.*?),");
return match.Success ? match.Groups[1].Value.Trim() : string.Empty;
}
}
}