Last active
May 8, 2023 17:19
-
-
Save scho/81bc72f04da9278d64d79eee1b328784 to your computer and use it in GitHub Desktop.
Unity UIToolkit Runtime Binding Extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Reflection; | |
using UnityEngine.UIElements; | |
namespace UI | |
{ | |
public static class BindingExtensions | |
{ | |
public static void Bind(this VisualElement element, object data) | |
{ | |
element.BindValues(data); | |
if (element.childCount == 0) | |
{ | |
return; | |
} | |
foreach (var child in element.Children()) | |
{ | |
child.Bind(data); | |
} | |
} | |
private static void BindValues(this VisualElement element, object data) | |
{ | |
if (element is Label label && label.bindingPath != null) | |
{ | |
foreach (var (name, value) in data.Values()) | |
{ | |
if (label.bindingPath.Equals(name)) | |
{ | |
label.text = (string) value; | |
} | |
} | |
} | |
} | |
private static IEnumerable<Tuple<string, object>> Values(this object data) | |
{ | |
foreach (var fieldInfo in data.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)) | |
{ | |
yield return Tuple.Create(fieldInfo.Name, fieldInfo.GetValue(data)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @FornostAD!
The approach in this gist just writes all the values from an object once into a VisualElement.
We no longer use this approach and use UniRx instead together with the following bits: