How can I store persistent references between VisualElements?
I extend VisualElement in a number of classes and some of them need to refer to one another. Sometimes, for example when I detach and reinsert the panel window that the elements live inside (DetachFromPanelEvent), the elements loose references to one another. Perhaps UIElements are destroying and recreating all elements in the background, what do I know.
In a MonoBehaviour I would use the [SerializeField] attribute, but how do I make sure references survive in a VisualElement?
VisualElement references are not serializable therefore using [SerializedField] won’t work. You shouldn’t loose references between VisualElements when detaching/reattaching a window (I am assuming here that you are talking about docking a window in the Unity Editor or making it floating) because this window isn’t actually destroyed (simply re-parented which sends a pair of DetatchFrom/AttachToPanel events.
To deal with when a recompilation or entering in playmode you will need to find a different another approach that relying on VisualElement objects as those definitely do not survive the C# domain reload. In this case EditorWindow.OnEnable() is the starting point when the whole UI needs to be created (just like the first time).
I would recommend using [SerializedField] in your custom window with types that can be serialized and somehow associated with the VisualElements you are about to create.
If you could explain a bit more broadly what you are trying to achieve I can provide some advice, in the mean time I hope this helps.
Thank you @antoine-unity for the elaborate answer, you are the best. Unfortunately I found out that I was removing the references between my VisualElements myself. I did this because I was confused by the inconsistency of the DetachFromPanelEvent, not always meaning that the element is removed.