99 lines
2.4 KiB
C#
99 lines
2.4 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace BITKit.UX
|
|
{
|
|
[AttributeUsage(AttributeTargets.Field|AttributeTargets.Property)]
|
|
public class UXBindPathAttribute : Attribute
|
|
{
|
|
public string Path;
|
|
public bool CanBeNull;
|
|
public UXBindPathAttribute(){}
|
|
public UXBindPathAttribute(string path)
|
|
{
|
|
Path = path;
|
|
}
|
|
public UXBindPathAttribute(string path,bool canBeNull)
|
|
{
|
|
Path = path;
|
|
CanBeNull = canBeNull;
|
|
}
|
|
}
|
|
public class UXUtils
|
|
{
|
|
public static void Inject(object self)
|
|
{
|
|
UIDocument document;
|
|
|
|
var field = self.GetType().GetField("document",
|
|
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
|
|
|
|
|
|
switch (field)
|
|
{
|
|
case null when self is MonoBehaviour monoBehaviour && monoBehaviour.TryGetComponent<UIDocument>(out document):
|
|
break;
|
|
case not null when field.GetValue(self) is UIDocument _document:
|
|
document = _document;
|
|
break;
|
|
default:
|
|
BIT4Log.Warning<UXUtils>($"document 未赋值或未找到");
|
|
return;
|
|
}
|
|
|
|
foreach (var fieldInfo in self.GetType()
|
|
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
|
|
.Where(x=>x.GetCustomAttribute<UXBindPathAttribute>() is not null)
|
|
)
|
|
{
|
|
var bindPathAtt = fieldInfo.GetCustomAttribute<UXBindPathAttribute>();
|
|
VisualElement ve = document.rootVisualElement;
|
|
foreach (var path in bindPathAtt.Path.Split("."))
|
|
{
|
|
ve = ve.Q(path);
|
|
}
|
|
//ve = document.rootVisualElement.Q(bindPathAtt.Path);
|
|
if(bindPathAtt.CanBeNull is false && ve is null)
|
|
BIT4Log.LogException(new NullReferenceException($"{self.GetType().Name}上未找到{bindPathAtt.Path}"));
|
|
|
|
if (fieldInfo.FieldType == typeof(UXContainer))
|
|
{
|
|
fieldInfo.SetValue(self, new UXContainer(ve));
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
fieldInfo.SetValue(self, ve);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
BIT4Log.Warning<UXUtils>(field!.Name);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
|
|
// if (field.GetValue(self) is not UIDocument _document)
|
|
// {
|
|
// if (self is MonoBehaviour monoBehaviour && (document = monoBehaviour.GetComponentInParent<UIDocument>()))
|
|
// {
|
|
// field.SetValue(self,document);
|
|
// }
|
|
// else
|
|
// {
|
|
// BIT4Log.Warning<UXUtils>($"document 未赋值");
|
|
// return;
|
|
// }
|
|
// }
|
|
|
|
}
|
|
}
|
|
}
|