Skip to content

BindableProperty

BindableProperty is a class used to specify data binding between elements on .uxml and the ViewModel.
When declared in a View class, the SourceGenerator collects the declared BindableProperty during initialization.
The declared BindableProperty will execute VisualElement.SetBinding() on the VisualElement.

How to Declare

To create a BindableProperty, call BindableProperty<T>.Create().

csharp
private static readonly BindableProperty<Label> LabelTextProperty =
    BindableProperty<Label>.Create(
        bindingId: PropertyPath.FromName(nameof(Label.text)),
        dataSourcePath: PropertyPath.FromName(nameof(ControlsShowcaseViewModel.Label)),
        elementNameInfo: ElementNames.Label,
        bindingMode: BindingMode.ToTarget,
        updateTrigger: BindingUpdateTrigger.OnSourceChanged
    );

Parameters

To allow flexible data binding, BindableProperty<T>.Create() can specify the following parameters:

ParameterTypeRequiredDefault Value
bindingIdBindingIdyes-
dataSourcePathPropertyPathyes-
elementNameInfoElementNameInfoyes-
bindingModeBindingModenoBindingMode.ToTarget
updateTriggerBindingUpdateTriggernoBindingUpdateTrigger.OnSourceChanged
  • bindingId
    Specifies which property of the VisualElement to bind to.
    In the example above, it specifies UnityEngine.UIElements.Label.text.

  • dataSourcePath
    Specifies which property declared in the ViewModel to bind to.
    In the example above, it specifies ControlsShowcaseViewModel.Label.

  • elementNameInfo
    Specifies which VisualElement to construct the binding for.
    You can also specify the name of the VisualElement as a string.
    To safely specify the string, a struct called ElementNames is generated by the SourceGenerator, where the names of VisualElements are declared.
    For details, see View source generation.

  • bindingMode
    Specifies BindingMode.
    Set appropriately depending on the type of VisualElement.
    For elements like Toggles that accept user input, setting BindingMode.TwoWay allows changes from both user actions and ViewModel operations to be reflected.

  • updateTrigger
    Specifies BindingUpdateTrigger.

Binding

The View class collects the declared BindableProperty and binds them as follows:

csharp
public override void FindElementAndSetBinding(VisualElement elementRoot)
{
    Elements = ElementNameInfo.Find<T>(elementRoot);
    foreach (var element in Elements)
    {
        element?.SetBinding(
            bindingId: BindingId,
            binding: new DataBinding()
            {
                bindingMode = BindingMode,
                dataSourcePath = DataSourcePath,
                updateTrigger = UpdateTrigger,
            }
        );
    }
}