Focus-event callback for TextField not working

Hi,

I’m really struggling on understanding how the focussing system works.

If I reference a focusable element in a custom component, and register the focus events, depending on the structure, sometimes the focus-event is called and sometimes it’s not.

Say, I have an Input component, that contains a Unity TextField component and adds/removes a class to it by registering a callback to the FocusEvents. While this works, it suddenly stops working if I hold a reference to my custom component in a different custom component.

To illustrate this, check out this minimal example project:

In the SampleScene the first field triggers the callback, while the second doesn’t (although it clearly has focus).

I found the canGrabFocus and delegatesFocus properties of VisualElements but neither found any good documentation of their usage nor did I manage to make good use of them.

I would appreciate any helpful input here!

No ideas on this? Did anyone try something similar and had any success? Someone from the Unity team maybe?

Hi seyfe,

The problem you’re having is that the OnInitialized method is not called at all on the first TextFieldContainer because it’s created using “new TextFieldContainer”, as opposed to being instiatiated by the UIDocument directly. When you’re using the constructor directly, there is no magic happening behind the scene, and the UxmlTraits.Init method is not used to initialize your element.

Hey Benoit,

now that you point it out, it’s pretty obvious… Thank you for taking your time to have a look!

I think I need to restructure the logic a bit. Probably it’s best to subscribe to the focus events when the visual input is set!