Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

c# - Do I need a BindingSource AND a BindingList for WinForms DataBinding?

I want to display a list of people in a DataGridView in a Windows Forms app. I want my service layer to return a list of Person objects (e.g., IList<Person>). I want changes in the list to be reflected in the DataGridView and vice versa. My understanding is that using the BindingSource facilitates working with DataGridView. My question is for the two-way databinding to work, do I need:

//pseudo code
BindingSource.DataSource = IBindingList<Person>

or can I do:

BindingSource.DataSource = IList<Person>

What's the difference? If my make changes to the list will the DataGridView be updated either way? And if I have to use the BindingList, it seems a little wonky (because of creating a dependency) to return a BindingList from my service layer, is there a way around that?

Microsoft says of the BindingList (in the Remarks section) http://msdn.microsoft.com/en-us/library/ms132679.aspx:

"However, the typical solutions programmer will use a class that provides data binding functionality, such as BindingSource, instead of directly using BindingList<T>."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Binding to an IList<Person> will only give you one-way binding; changes to the list or list items will not be reflected in the DataGridView. You can use a BindingList or BindingSource to get this functionality instead, but your Person class will still need to support INotifyPropertyChanged or else you will only get synchronisation when items are added/removed to/from the list, not when the list items themselves change.

If you want to avoid a dependency on System.Windows.Forms, you could use ObservableCollection<Person> instead; this supports the necessary change notifications and can therefore be used as a two-way binding source.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...