包含此页的版本:
不含此页的版本:
您可以使用VisualElement.customStyle属性来获取应用于元素的自定义样式属性(变量)的值。但是,您不能像使用VisualElement.style或VisualElement.resolvedStyle. 相反,请执行以下作:
CustomStyleResolvedEvent事件。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();
}
}
}