How to strongly type data binding in C# WinForms?

We've been using WinForms data binding for a few months, and run into some problems:

  • Lack of strong typing
  • Unable to bind controls to complex properties (models/collections of models)
  • Difficulties customizing behaviour for null values & special requirements
  • Creates .datasource files which bloat solution
  • Operates as a “black box” – difficult to diagnose issues or tweak functionality
  • We're considering building a data binding utility which is customized for our user controls & models. This would be strongly typed via lambda functions, able to bind complex properties, and allow for any other special functionality we need. Binding could occur with something roughly 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 the pitfalls?

    2) Is there a 3rd party utility out there which does all this already?

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


    Strongly opinionated answer ahead:

    I have tried a few different approaches to binding in WinForms (over many years), and it ends up being really easy to get 80% of what you want, and it requires significant hacking to make the other 20% work. Also, usually 3rd party controls come with their own quirks.

    Your list there illustrates the pitfalls fairly well. Unfortunately, WinForms just doesn't have the binding power of, say, WPF.

    My current approach to data binding is to do not use any of the binding objects and do everything manually. The approach I usually take is just make the form a passive view and pass the Form a ViewModel object encapsulating all the data that should be displayed on the form and set all the properties on the form from that object. Which means you lose all the 'magic' of binding, but it's not a black box anymore and it's easier to debug.

    Good question, I look forward to other answers and being proved wrong.

    链接地址: http://www.djcxy.com/p/29184.html

    上一篇: 可检查的业务对象到网格

    下一篇: 如何在C#WinForms中强类型数据绑定?