C#에서 시각적 요소의 프로퍼티를 데이터 소스에 바인딩하려면 DataBinding의 인스턴스를 생성합니다. 이 바인딩 타입을 사용하면 바인딩 인스턴스에서 직접 dataSource 및 dataSourcePath를 정의할 수 있습니다.
C#에서 런타임 바인딩을 생성하려면 다음 단계를 따르십시오.
다음 예시에서는 바인딩 오브젝트를 생성하여 시각적 요소에 등록합니다.
var dataSource = ScriptableObject.CreateInstance<ExampleObject>();
var root = new VisualElement
{
name = "root",
dataSource = dataSource
};
var vector3Field = new Vector3Field("Vec3 Field");
vector3Field.SetBinding("label", new DataBinding
{
dataSourcePath = new PropertyPath(nameof(ExampleObject.vector3Label)),
bindingMode = BindingMode.ToTarget
});
vector3Field.SetBinding("value", new DataBinding
{
dataSourcePath = new PropertyPath(nameof(ExampleObject.vector3Value))
});
root.Add(vector3Field);
var floatField = new FloatField("Float Field") { value = 42.2f };
floatField.SetBinding("value", new DataBinding
{
dataSourcePath = new PropertyPath(nameof(ExampleObject.sumOfVector3Properties))
});
root.Add(floatField);
var label = new Label("Label")
{
dataSourcePath = new PropertyPath(nameof(ExampleObject.dangerLevel))
};
// Here, we do not need to set the dataSourcePath because we will only use two bindings and they will use the same path,
// so we set the dataSourcePath on the Label directly instead.
var binding = new DataBinding
{
bindingMode = BindingMode.ToTarget
};
// Add a custom float -> string converter
binding.sourceToUiConverters.AddConverter((ref float v) =>
{
return v switch
{
>= 0 and < 1.0f/3.0f => "Danger",
>= 1.0f/3.0f and < 2.0f/3.0f => "Neutral",
_ => "Good"
};
});
// Add a custom float -> StyleColor
binding.sourceToUiConverters.AddConverter((ref float v) => new StyleColor(Color.Lerp(Color.red, Color.green, v)));
// Since the binding is targeting the same data source property, we can re-use the same instance.
label.SetBinding("text", binding);
label.SetBinding("style.backgroundColor", binding);
root.Add(label);
이는 다음 UXML과 동일합니다.
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements"
editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
<ui:VisualElement data-source="ExampleObject.asset" name="VisualElement" >
<ui:Vector3Field label="Vec3 Field">
<Bindings>
<ui:DataBinding property="label" data-source-path="vector3Label" binding-mode="ToSource" />
<ui:DataBinding property="value" data-source-path="vector3Value" />
</Bindings>
</ui:Vector3Field>
<ui:FloatField label="Float Field" value="42.2">
<Bindings>
<ui:DataBinding property="value" data-source-path="sumOfVector3Properties" binding-mode="ToTarget" />
</Bindings>
</ui:FloatField>
<ui:Label text="Label" data-source-path="dangerLevel">
<Bindings>
<ui:DataBinding property="text" binding-mode="ToTarget" source-to-ui-converters="Value To Progress" />
<ui:DataBinding property="style.backgroundColor" binding-mode="ToTarget" source-to-ui-converters="Value To Progress" />
</Bindings>
</ui:Label>
</ui:VisualElement>
</ui:UXML>
다음 메서드를 사용하여 바인딩 오브젝트를 관리할 수 있습니다.
다른 데이터 소스와 동일한 방식으로 바인딩 가능한 프로퍼티를 생성할 수 있습니다. 즉, VisualElement 타입을 데이터 소스로 사용할 수도 있습니다. VisualElement 타입과 다른 데이터 소스의 주요 차이점은 VisualElement 타입이 빌트인 버전 관리 기능과 함께 제공되는 것입니다. 변경 사항을 전파하려면 VisualElement 타입의 빌트인 버전 관리 기능을 사용해야 합니다.
변경 사항을 보고하려면 NotifyPropertyChanged 메서드를 호출합니다. 이 메서드는 변경된 프로퍼티를 식별하는 BindingId를 사용합니다. 다음 예시에서는 변경 사항을 리포트하는 방법을 보여 줍니다.
// Creates a static readonly BindingId that is unique to this type. This is used to identify the property.
public static readonly BindingId intValueProperty = nameof(intValue);
private int m_IntValue;
[CreateProperty]
public int intValue
{
get => m_IntValue;
set
{
if (m_IntValue == value)
return;
m_IntValue = value;
// This instructs the binding system that a change occured.
NotifyPropertyChanged(intValueProperty);
}
}
다음 팁과 베스트 프랙티스를 따라 성능을 최적화하십시오.
Vector3Field의 value 프로퍼티에 바인딩하려면 바인딩 ID가 Vector3Field.valueProperty여야 합니다.Vector3Field의 x, y, z 하위 요소를 동기화하지 마십시오. 대신 바인딩을 사용하여 Vector3Field의 value 프로퍼티를 데이터 소스의 Vector3 프로퍼티와 동기화합니다.UI 툴킷은 element.style 및 element.resolvedStyle의 변경 사항을 보고하지 않습니다. 따라서 바인딩 인스턴스를 사용하여 요소의 확인된 스타일을 타게팅할 수 있지만 변경 사항은 추적할 수 없습니다.