Changing an image texture by code

Hi there I am trying to implement simple functionally but I am unable to make it. I have a list view with some elements and that elements have an image (Since there is no control for images, I have a Visualelement with a background image).

I will like to change the image texture by code but I am unable to access that property

I have tried the following code but StyleBackground is not a variable. Any help will be appreciated

    VisualElement mainImg = adapter.Q<VisualElement>("MainImg");

        StyleBackground background = mainImg.style.backgroundImage;
        background.value.texture = module.moduleIcon;

This should be enough:

mainImg.style.backgroundImage = module.moduleIcon;

StyleBackground is a struct so if you assign it to a variable (your “background” variable) and then change one of its fields, your mainImg element will not know anything about it. Structs in c# are copied like a value, not referenced.

Also, when you do style.backgroundImage = something, there’s a custom cast operator= that converts your “something” Texture2D to a StyleBackground. So you don’t need to “new StyleBackground()” or anything like that. Same goes for all other style properties.

1 Like