可以使用 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();
}
}
}