Accessing children in custom c# element

I have created my custom VisualElement(code below) and I want to bind events to my buttons that I add directly into my UXML document, like following:
9492826--1336399--upload_2023-11-25_18-11-37.png

is there any way to access those buttons in that script?

public class MenuWithIndicator : VisualElement
{
    public new class UxmlFactory : UxmlFactory<MenuWithIndicator, UxmlTraits> { }

    private List<Button> m_Buttons;
    private VisualElement m_Indicator;

    public MenuWithIndicator()
    {
        AppendIndicator();

        // buttons don't exist yet
    }

    // temporary solution
    public void BindButtonEvents()
    {
        m_Buttons = Children().OfType<Button>().ToList();
        foreach (Button button in m_Buttons)
        {
            button.RegisterCallback<PointerEnterEvent>((e) => { OnButtonHover(e.target as Button); });
        }
    }

    private void AppendIndicator()
    {
        m_Indicator = new VisualElement()
        {
            name = "Indicator",
            style =
            {
                height = 20,
                width = 2,
                backgroundColor = Color.white,
                position = Position.Absolute,
                marginLeft = 5
            }
        };

        Add(m_Indicator);
    }

    private void OnButtonHover(Button button)
    {
        if (m_Indicator == null)
            return;

        m_Indicator.style.top = button.layout.yMin;
    }
}

Register a AttachToPanelEvent callback in your constructor and do the initialisation there.

1 Like

Thanks, works fine.