Skip to content

BindableProperty

BindablePropertyは.uxml上の要素とViewModelのデータバインディングを指定するためのクラスです。
Viewクラスに宣言することで、SourceGeneratorが初期化時に宣言されたBindablePropertyを収集します。
宣言されたBindableProperty がVisualElementに対してVisualElement.SetBinding() を実行します。

宣言の方法

BindablePropertyを作成するには 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

柔軟にデータバインディングを指定できるように、BindableProperty<T>.Create()は次のパラメータを指定することができます。

パラメータ必須初期値
bindingIdBindingIdyes-
dataSourcePathPropertyPathyes-
elementNameInfoElementNameInfoyes-
bindingModeBindingModenoBindingMode.ToTarget
updateTriggerBindingUpdateTriggernoBindingUpdateTrigger.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を収集し、次のような紐づけを行います。

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,
                    }
                );
            }
        }