54 lines
1.9 KiB
C#
54 lines
1.9 KiB
C#
|
|
using Avalonia.Controls;
|
|||
|
|
using Avalonia.Controls.Templates;
|
|||
|
|
using Avalonia_PC.ViewModels;
|
|||
|
|
using System;
|
|||
|
|
using System.Diagnostics.CodeAnalysis;
|
|||
|
|
|
|||
|
|
namespace Avalonia_PC
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// Given a view model, returns the corresponding view if possible.
|
|||
|
|
/// </summary>
|
|||
|
|
[RequiresUnreferencedCode(
|
|||
|
|
"Default implementation of ViewLocator involves reflection which may be trimmed away.",
|
|||
|
|
Url = "https://docs.avaloniaui.net/docs/concepts/view-locator")]
|
|||
|
|
/// <summary>
|
|||
|
|
/// 视图定位器,根据 ViewModel 类型自动查找对应的 View,
|
|||
|
|
/// 实现 IDataTemplate 以支持 Avalonia 的数据模板机制。
|
|||
|
|
/// </summary>
|
|||
|
|
public class ViewLocator : IDataTemplate
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 根据 ViewModel 实例构建对应的 View 控件。
|
|||
|
|
/// 约定:将 ViewModels 命名空间中的 ViewModel 替换为 Views 命名空间中的同名 View。
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="param">ViewModel 实例。</param>
|
|||
|
|
/// <returns>对应的 View 控件;若未找到则返回 TextBlock 显示错误信息。</returns>
|
|||
|
|
public Control? Build(object? param)
|
|||
|
|
{
|
|||
|
|
if (param is null)
|
|||
|
|
return null;
|
|||
|
|
|
|||
|
|
var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
|
|||
|
|
var type = Type.GetType(name);
|
|||
|
|
|
|||
|
|
if (type != null)
|
|||
|
|
{
|
|||
|
|
return (Control)Activator.CreateInstance(type)!;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return new TextBlock { Text = "Not Found: " + name };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 判断数据对象是否为 ViewModel 类型(以 "ViewModel" 结尾)。
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="data">要判断的数据对象。</param>
|
|||
|
|
/// <returns>是否为 ViewModel。</returns>
|
|||
|
|
public bool Match(object? data)
|
|||
|
|
{
|
|||
|
|
return data is ViewModelBase;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|