Get custom styles in C# scripts
Understand how to get the value of a custom style property applied to an element.
Read time 1 minuteLast updated 22 days ago
You can use the property to get the value of a custom style property (variables) applied to an element. However, you can't directly query it as you would with or . Instead, do the following:
VisualElement.customStyleVisualElement.styleVisualElement.resolvedStyle- Register to the event.
CustomStyleResolvedEvent - Call the method to query the returned object of the
TryGetValuesproperty.element.customStyle
Assume you have defined a custom style property in USS like this:
--my-custom-color.my-selector{ --my-custom-color: red;}
The following example class shows how to get the value of applied to an element:
--my-custom-colorpublic 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(); } }}