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()
.
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:
Parameter | Type | Required | Default Value |
---|---|---|---|
bindingId | BindingId | yes | - |
dataSourcePath | PropertyPath | yes | - |
elementNameInfo | ElementNameInfo | yes | - |
bindingMode | BindingMode | no | BindingMode.ToTarget |
updateTrigger | BindingUpdateTrigger | no | BindingUpdateTrigger.OnSourceChanged |
bindingId
Specifies which property of the VisualElement to bind to.
In the example above, it specifiesUnityEngine.UIElements.Label.text
.dataSourcePath
Specifies which property declared in the ViewModel to bind to.
In the example above, it specifiesControlsShowcaseViewModel.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 calledElementNames
is generated by the SourceGenerator, where the names of VisualElements are declared.
For details, see View source generation.bindingMode
SpecifiesBindingMode
.
Set appropriately depending on the type of VisualElement.
For elements like Toggles that accept user input, settingBindingMode.TwoWay
allows changes from both user actions and ViewModel operations to be reflected.updateTrigger
SpecifiesBindingUpdateTrigger
.
Binding
The View class collects the declared BindableProperty
and binds them as follows:
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,
}
);
}
}