From 5c7f6ba6e8837d303686711b5144820667560f68578f0d58b94fcd37e73472de Mon Sep 17 00:00:00 2001 From: copecone Date: Fri, 12 Jun 2026 14:22:32 +0900 Subject: [PATCH] Add `EnumDropdownBinder` --- Data/EnumDropdownBinder.cs | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Data/EnumDropdownBinder.cs diff --git a/Data/EnumDropdownBinder.cs b/Data/EnumDropdownBinder.cs new file mode 100644 index 0000000..f449442 --- /dev/null +++ b/Data/EnumDropdownBinder.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using MelonLoader; +using UnityEngine.UIElements; + +namespace ADOFAIRenderer.Data +{ + /// + /// Binds a UI Toolkit to an enum type. + /// Populates choices from enum names and provides typed access to the selected value. + /// + /// The enum type to bind. + public class EnumDropdownBinder where T : struct, Enum + { + private readonly DropdownField _dropdown; + private readonly List _values; + + /// + /// The currently selected enum value. + /// + public T Value => _values[_dropdown.index >= 0 ? _dropdown.index : 0]; + + /// + /// Queries a by name from the root VisualElement, + /// populates it with enum names, and selects the default value. + /// + /// The root VisualElement loaded from the UXML bundle. + /// The name of the DropdownField in the UXML. + /// The initial selected value. Defaults to the first enum member. + public EnumDropdownBinder(VisualElement rootVisualElement, string fieldName, T? defaultValue = null) + { + _dropdown = rootVisualElement.Q(fieldName); + if (_dropdown == null) + { + Melon.Logger.Error( + $"DropdownField '{fieldName}'을(를) 찾을 수 없습니다."); + _values = new List(); + return; + } + + _values = Enum.GetValues(typeof(T)).Cast().ToList(); + _dropdown.choices = _values.Select(v => v.ToString()).ToList(); + + var initial = defaultValue ?? _values[0]; + _dropdown.index = _values.IndexOf(initial); + } + + /// + /// Registers a callback that fires when the selection changes, providing the new enum value. + /// + public void OnValueChanged(Action callback) + { + _dropdown?.RegisterValueChangedCallback(evt => + { + callback(Value); + }); + } + } +}