Hi @owen.campbell,
Yes, creating a form (or a component, which is the same thing as far as Anvil is concerned) in code is entirely supported! You’re doing exactly the right thing - just inherit from the base component you want to inherit from, and set up your components in your __init__
.
However, you can’t create data bindings this way, because data bindings are part of the drag-and-drop designer rather than the code. In much the same way that placing components in the designer is “GUI sugar” for writing a bunch of self.add_component(...)
calls in your __init__
function, data bindings are just a GUI way to do things you can do from code: namely, updating component properties from code, or updating data when component events fire.
For example, let’s imagine that I have a TextBox on my form, with its text
property data-bound to self.foo
, with write-back enabled. The equivalent code is something like:
class MyForm(ColumnPanel):
def __init__(self, **properties):
self.foo = "bar"
self.text_box_1 = TextBox()
self.text_box_1.add_event_listener('lost_focus', self.text_box_1_writeback)
self.refresh_data_bindings()
def refresh_data_bindings(self):
self.text_box_1.text = self.foo
def text_box_1_writeback(self, **event_args):
self.foo = self.text_box_1.text
As you can see, there’s nothing really special about data bindings. They’re just a way of automatically generating some event handlers and a list of assignment statements to run when refresh_data_bindings()
is called.
The only other piece of “sugar” is the item
property that is automatically created on every Form created with the designer. In fact, the only special thing about the item
property is that it calls refresh_data_bindings()
every time you set it. We could do that ourselves if we wanted, with the @property
decorator:
def __init__(self):
# ...whatever else you want to do...
self._item = {}
@property
def item(self):
return self._item
@item.setter
def item(self, new_value):
self._item = new_value
self.refresh_data_bindings()
That’s all there is! There is no man behind the curtain. Data Bindings are just a designer shortcut for code you could write yourself.