Adding data bindings via code

Yes! Data bindings are basically an abstraction in the form designer - you could create the same effect just by writing code. If I data-bind the text property of a Label to the expression self.foo, this is the equivalent of adding some code to the refreshing_data_bindings event:

  def form_refreshing_data_bindings (self, **event_args):
    # This method is called when refreshing_data_bindings is called
    self.label_1.text = self.foo

(The refreshing_data_bindings event is triggered when you call the refresh_data_bindings() method, or when you update the item property on a form.)

If you have a data binding with write-back (eg on a TextBox), it’s as if you’ve added the following code:

  def text_box_1_lost_focus (self, **event_args):
    # This method is called when the TextBox loses focus
    self.foo = self.text_box_1.text

(When precisely a data binding writeback occurs is determined by the component. TextBoxes and TextAreas write back when they lose focus, whereas CheckBoxes and DropDowns write back on the change event.)

That’s it! There’s nothing more magic about data bindings – it’s just an assignment, triggered off events. This means that you can do whatever you like in code, depending on what you want to do.

So…what do you want to do? Is there a design pattern we can help you with?

2 Likes