How to strongly introduce data binding in C # WinForms?

We have been using WinForms data binding for several months and are facing some problems:

  • Lack of strong typing
  • Cannot associate controls with complex properties (models / model collections)
  • Difficulty adjusting behavior for null values ​​and special requirements
  • Creates .datasource files that inflate the solution
  • Works like a black box - it's hard to diagnose problems or configure features.

We looked at creating a data binding utility that is customizable for our custom controls and models. This will be strongly typed using lambda functions that can bind complex properties and allow any other special functionality that we need. Linking can occur with something like the following:

var binder = new Binder<Person>(); binder.Bind (p => p.FirstName, FirstNameText); binder.Bind (p => p.Surname, SurnameText); binder.Bind (p => p.BirthDate, BirthDatePicker); binder.Bind (p => p.PersonType, PersonTypePicker); <-- Binds direct to PersonType model – not PersonTypeId value binder.Bind (p => p.Interests, InterestsPicker); <-- Binds collection property to control's collection property (automatically sync's contents) binder.DataSource = _selectedPerson; 

Questions:

1) Is this approach recommended or are pitfalls?

2) Is there a third-party utility that does all this already?

3) How do you deal with the complex data binding requirements of your projects?

+4
source share
1 answer

A very stubborn answer ahead:

I tried several different binding approaches in WinForms (over the years), and it is actually very easy to get 80% of what you want, and it requires a significant hack for the other 20% to work. In addition, usually third-party controls have their own quirks.

Your list there illustrates well the pitfalls. Unfortunately, WinForms simply does not have the ability to bind, say, WPF.

My current approach to data binding is to not use any binding objects and do everything manually. The approach that I usually do is simply make the form a passive view and pass the ViewModel form object, encapsulating all the data that should be displayed on the form and setting all the properties on the form from this object. This means that you lose all the β€œmagic” of the binding, but it is not a black box and it is easier to debug.

Good question, I look forward to other answers and it turned out to be wrong.

+3
source

Source: https://habr.com/ru/post/1484754/


All Articles