开发者

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 clien开发者_开发百科t 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜