The “background-image” css property can be properly assigned in a normal uss stylesheet with multiple interpretations of the string (Resource or Url).
I’m trying to create several custom visual elements that are to have an Icon field and layout styles for it’s placement relative to text(upper-left | middle-left | lower-left | upper-center | middle-center | lower-center | upper-right | middle-right | lower-right)
I want to make them work, as seamlessly as possible, like the background-image uss attribute.
I want to simply be able to use:
icon-align: middle-left```or
```icon-image: url("Images/my-image.png")```
Then add a UxmlIconAttributeDescription to my custom visual elements with everything just working, including in the UI Builder. I know this could be implemented in raw Visual Elements alone without extending uss, but I'm anticipating having to do this in a lot of visual elements in several tools spread out over months and I loathe code duplication instances in large projects. Code translation copy-paste is such a bug magnet.
Custom USS properties are possible but not well supported just yet.
They require some custom event handling code and unfortunately UI Builder will not detect them yet.
In short, you typically use those in a custom VisualElement :
class MyCustomElement : VisualElement
{
static CustomStyleProperty<Texture2D> s_IconImage = new CustomStyleProperty<Texture2D>("--icon-image");
static CustomStyleProperty<string> s_IconAlign = new CustomStyleProperty<Texture2D>("--icon-align");
public MyCustomElement()
{
RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
}
private void CustomStyleResolvedEvent(CustomStyleResolvedEvent evt)
{
Texture2D textureValue = null;
if (evt.TryGetValue(s_IconImage, out textureValue))
{
// do stuff with texture
}
string align;
if (evt.TryGetValue(s_IconAlign, out align))
{
// parse align to enum
}
}
}
We have plans to better integrate custom USS properties into C# which will make it easier for UI builder to detect them. You can use them in raw USS though:
.custom-element-instance {
--icon-image: url("...");
}
2 Likes