Skip to content

Instantly share code, notes, and snippets.

@scho
Last active May 8, 2023 17:19
Show Gist options
  • Save scho/81bc72f04da9278d64d79eee1b328784 to your computer and use it in GitHub Desktop.
Save scho/81bc72f04da9278d64d79eee1b328784 to your computer and use it in GitHub Desktop.
Unity UIToolkit Runtime Binding Extension
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));
}
}
}
}
@scho
Copy link
Author

scho commented Oct 18, 2022

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment