Version: 6000.3
语言: 中文
USS 内置变量引用
在 C# 脚本中应用样式

在 C# 脚本中获取自定义样式

您可以使用VisualElement.customStyle属性来获取应用于元素的自定义样式属性(变量)的值。但是,您不能像使用VisualElement.styleVisualElement.resolvedStyle. 相反,请执行以下作:

  1. 注册到CustomStyleResolvedEvent事件。
  2. 调用TryGetValues方法来查询返回的对象element.customStyle财产。

假设您定义了自定义样式属性--my-custom-color在 USS 中,像这样:

.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();
        }
    }
}

其他资源

USS 内置变量引用
在 C# 脚本中应用样式