Winforms Databinding with ViewModel

I have a list of classes that represent mydatabase tables, for example Address, Client.

My GUI tends to be a data grid and a form of data entry. This works fine for entering data with a single table, but now I have a form in which there is customer information and their address.

I was thinking about using a ViewModel that combines the Address and Client class, and assigning this source to bind and bind controls to it.

How to associate controls with property names? Will it work ...

if (txtLine1.DataBindings.Count == 0) txtLine1.DataBindings.Add("Text", bindingSource, "Address.Line1", false, DataSourceUpdateMode.OnPropertyChanged); 

Does ViewModel even have the ability to bind Winforms data?

+4
source share
2 answers

I created a ViewModel and then created a DataSource in VS. Then I dragged the class properties in my viewmodel into the form and created the created controls. Then I call the Save method for each class in my view model.

+2
source

If you use the VS constructor, you can set the binding using this in the control's binding property - let the template code be created by VS if it does not bind something in the constructor and does not check the generated code. Just add a BindingSource to your form and bind it to the properties. Then set the BindingSource.DataSource parameter when you have ViewModel.

The key to binding to ViewModel in WinForms is the implementation of the INotifyPropertyChange interface and the triggering of the PropertyChanged event in the settings of all your properties on the model, passing the property name as a string. This event is captured by any WinForms controls that will be updated if you change anything on the model. It also means that you can catch the event on the presenter, if any, and perform any calculations / actions there.

+1
source

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


All Articles