VisualElement.customStyle プロパティを使用して、要素に適用された カスタムスタイルプロパティ (変数) の値を取得できます。ただし、VisualElement.style や VisualElement.resolvedStyle のように直接クエリすることはできません。代わりに、以下の手順に従います。
CustomStyleResolvedEvent イベントに登録します。TryGetValues メソッドを呼び出し、element.customStyle プロパティの返されたオブジェクトをクエリします。USS でカスタムスタイルプロパティ --my-custom-color を以下のように定義したとします。
.my-selector
{
--my-custom-color: red;
}
以下のサンプルクラスは、要素に適用された --my-custom-color の値を取得する方法を示しています。
public class HasCustomStyleElement : VisualElement
{
// Custom style property definition from code indicating the type and the name of the property.
private static readonly CustomStyleProperty<Color> s_CustomColor = new ("--my-custom-color");
private Color customColor { get; set; }
public HasCustomStyleElement()
{
RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
}
private void OnCustomStyleResolved(CustomStyleResolvedEvent evt)
{
// If the custom style property is resolved for this element, you can query its value through the `customStyle` accessor.
if (evt.customStyle.TryGetValue(s_CustomColor, out var value))
{
customColor = value;
}
// Otherwise, put some default value.
else
{
customColor = new Color();
}
}
}