User Tools

Site Tools


winforms_databinding_sample

WinForms Databinding

The databinding in WinForms is not so advanced like the databinding in WPF, but it is possible. The data object on which the controls content can be bound (usually called ViewModel in MVVM terms) needs to implement the INotifyPropertyChanged interface.

As usual, it requires at least one line of code for every field:

oTextBox:Bindings:Add( "Text", oViewModel, "PropertyName" )

where Text stands for the property of the TextBox on which the ViewModel field has to be bound, and FieldName stands for the name of the property in the ViewModel that contains the desired value.

It is very easy to implement name based binding in WinForms. You need a similar method of ther following in your window:

method Use( oViewModel as INotifyPropertyChanged ) as void 
local oControls as System.Windows.Forms.Control.ControlCollection
local oTextBox as TextBox
 
oControls := self:Controls
foreach oControl as Control in oControls 
  do case
  case oControl is TextBox
    oTextBox := ( TextBox ) oControl
    oTextBox:DataBindings:Add( "Text", oViewModel, oTextBox:Name )
  endcase
 
next
 
return

and then you can combine your form (or View as in MVVM) with a simple statement:

oForm:Use( oViewModel )

Of course you should enhance your method to implement databinding also for the other types of controls you use, and you should put them in your windows base class from which all your forms/Views will be inherited.

A sample as XIDE export file can be found here: winformsdatabindingapp.zip

winforms_databinding_sample.txt · Last modified: 2018/07/29 05:28 by wolfgangriedmann