简体   繁体   中英

Winforms Databinding with a ViewModel

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

My GUI tends to be a grid of data and an data entry form. This works fine for single table data entry however I now have a form that has client information and their address.

I was thinking of using a ViewModel combining the Address and Client class and assigning that to a bindingsource and binding my controls to that.

How would I bind the controls to the property names? Would this work...

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

Is having a ViewModel even possible for Winforms databinding?

I created a ViewModel and then created a DataSource in VS. I then dragged the properties of the classes in my viewmodel to the form and this created the controls I needed. I then call the Save method for each class in my viewmodel.

If you're using the VS designer you can set the binding up using that in the databinding property of the control - let the boilerplate code be generated by VS, if not bind something in the designer and check out the generated code. Simply add a BindingSource to your form and bind to the properties on that. Then set BindingSource.DataSource when you have the ViewModel.

The key to binding to a ViewModel in WinForms is to implement the interface INotifyPropertyChange and trigger the PropertyChanged event in the setters of all your properties on the model, passing in the name of the property as a string. This event is caught by any WinForms controls which will update should you change anything on the model. This also means that you can catch the event on the presenter if you have one and perform any calculations/actions up there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM