So, form your snippets, you are defining both the dataSourcePath
on the element and on the binding. This will result in the resolved path being _foo._foo
, this is one _foo
too many.
What I meant is that the preferred way to avoid the code boiler plate would be to setup the binding object in uxml directly. That way, you can instantiate your uxml file, set the data source without having to add bindings manually.
If your data happens to be a scriptable object, you can also reference it from uxml as well to set it as a data source. This is not a mandatory step. This is also a limitation of the uxml asset, because it can only reference other assets and not arbitrary data. From code, you can set arbitrary data as a data source.
Starting from your example, you could do something like this:
UXML:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<ui:FloatField label="Foo" value="42.2">
<Bindings>
<ui:smile:ataBinding property="value" data-source-path="_foo"/>
</Bindings>
</ui:FloatField>
</ui:UXML>
C#:
public class UITest : MonoBehaviour
{
[SerializeField] private float _foo;
private void Start()
{
var doc = GetComponent<UIDocument>();
doc.rootVisualElement.dataSource = this; // With only this line, and the UXML, nothing happens.
}
}
The data-source-type
is there for the UI Builder purposes, it allows the use of auto-complete when you know which type you intend to use at runtime, but can’t link in your uxml.