SHA256
61 lines
2.3 KiB
C#
61 lines
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using MelonLoader;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace ADOFAIRenderer.Data
|
|
{
|
|
/// <summary>
|
|
/// Binds a UI Toolkit <see cref="DropdownField"/> to an enum type.
|
|
/// Populates choices from enum names and provides typed access to the selected value.
|
|
/// </summary>
|
|
/// <typeparam name="T">The enum type to bind.</typeparam>
|
|
public class EnumDropdownBinder<T> where T : struct, Enum
|
|
{
|
|
private readonly DropdownField _dropdown;
|
|
private readonly List<T> _values;
|
|
|
|
/// <summary>
|
|
/// The currently selected enum value.
|
|
/// </summary>
|
|
public T Value => _values[_dropdown.index >= 0 ? _dropdown.index : 0];
|
|
|
|
/// <summary>
|
|
/// Queries a <see cref="DropdownField"/> by name from the root VisualElement,
|
|
/// populates it with enum names, and selects the default value.
|
|
/// </summary>
|
|
/// <param name="rootVisualElement">The root VisualElement loaded from the UXML bundle.</param>
|
|
/// <param name="fieldName">The name of the DropdownField in the UXML.</param>
|
|
/// <param name="defaultValue">The initial selected value. Defaults to the first enum member.</param>
|
|
public EnumDropdownBinder(VisualElement rootVisualElement, string fieldName, T? defaultValue = null)
|
|
{
|
|
_dropdown = rootVisualElement.Q<DropdownField>(fieldName);
|
|
if (_dropdown == null)
|
|
{
|
|
Melon<RenderMod>.Logger.Error(
|
|
$"DropdownField '{fieldName}'을(를) 찾을 수 없습니다.");
|
|
_values = new List<T>();
|
|
return;
|
|
}
|
|
|
|
_values = Enum.GetValues(typeof(T)).Cast<T>().ToList();
|
|
_dropdown.choices = _values.Select(v => v.ToString()).ToList();
|
|
|
|
var initial = defaultValue ?? _values[0];
|
|
_dropdown.index = _values.IndexOf(initial);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Registers a callback that fires when the selection changes, providing the new enum value.
|
|
/// </summary>
|
|
public void OnValueChanged(Action<T> callback)
|
|
{
|
|
_dropdown?.RegisterValueChangedCallback(evt =>
|
|
{
|
|
callback(Value);
|
|
});
|
|
}
|
|
}
|
|
}
|