Search Unity

Can you bind to properties, or just fields?

Discussion in 'UI Toolkit' started by mikevargas, Aug 18, 2019.

  1. mikevargas

    mikevargas

    Joined:
    Aug 17, 2019
    Posts:
    22
    I've noticed that if I have a simple binding to a TextField, from a simple string field (of a ScriptableObject in my case), the binding works as expected and the contents of the string field of the ScriptableObject are reflected in the TextField.

    But if I instead change the field to a property (i.e. adding {get;set;} to the end of its declaration), the TextField does not reflect the contents of the variable (it's empty).

    How can I get bindings to work for properties? Side note: If this is not supported, the documentation should really change its language since it's full of references to "properties" when discussing binding sources, and that's not the correct nomenclature in C#.
     
    Last edited: Aug 18, 2019
    StephanieRowlinson likes this.
  2. larsolm5853

    larsolm5853

    Joined:
    Oct 24, 2017
    Posts:
    21
    Bindings act based on "SerializedProperties" which understandably can be confusing. So unfortunately since C# properties themselves are not serializable, then they cannot be used as the binding for a control :( You will have to manually create the private backing field of a public property, mark it as [SerializeField], and then you will be able to bind to that just like a regular public field.
     
    mikevargas likes this.
  3. mikevargas

    mikevargas

    Joined:
    Aug 17, 2019
    Posts:
    22
    Thank you very much for that explanation. I'm accustomed to Windows Presentation Foundation (WPF) applications, so it was a bit of a surprise with the different behavior. Still, I think I can accomplish what I need: I'm trying to perform some operations whenever the value of a bound property changes (hence the desire for C# properties, since I can add behavior to their setters).

    It turns out that for my purposes, it should be enough to just register a Changed event handler to the root VisualElement of my custom editor window, and then perform whatever operations I need whenever the value of a control changes.

    Thanks again.