BindableProperty
BindablePropertyは.uxml上の要素とViewModelのデータバインディングを指定するためのクラスです。
Viewクラスに宣言することで、SourceGeneratorが初期化時に宣言されたBindablePropertyを収集します。
宣言されたBindableProperty がVisualElementに対してVisualElement.SetBinding() を実行します。
宣言の方法
BindablePropertyを作成するには 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
柔軟にデータバインディングを指定できるように、BindableProperty<T>.Create()は次のパラメータを指定することができます。
| パラメータ | 型 | 必須 | 初期値 |
|---|---|---|---|
| bindingId | BindingId | yes | - |
| dataSourcePath | PropertyPath | yes | - |
| elementNameInfo | ElementNameInfo | yes | - |
| bindingMode | BindingMode | no | BindingMode.ToTarget |
| updateTrigger | BindingUpdateTrigger | no | BindingUpdateTrigger.OnSourceChanged |
bindingId
バインディングするVisualElementの、どのプロパティに対してバインディングするかを指定します。
上記の例ではUnityEngine.UIElements.Label.textを指定しています。dataSourcePath ViewModelに宣言されたどのプロパティをバインディングするかを指定します。
上記の例ではControlsShowcaseViewModel.Labelを指定しています。elementNameInfo どのVisualElementに対してバインディングを構築するかを指定します。
ここにはVisualElementの名前を文字列で指定することもできます。
文字列を安全に指定できるようにするためにSourceGeneratorによってElementNamesという構造体が作成され、VisualElementの名前が宣言されています。
詳細は、View source generationを確認してください。bindingMode
BindingModeを指定します。
対象にしたいVisualElementの種類によって、適切に設定してください。
例えば、Toggleなどユーザー操作を受ける要素についてはBindingMode.TwoWayを設定することでユーザー操作とViewModelの操作の両方からの変更を反映することができます。updateTrigger
BindingUpdateTriggerを指定します。
紐づけ
Viewクラスは宣言されたBindablePropertyを収集し、次のような紐づけを行います。
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,
}
);
}
}