I've recently been using data binding in c#, and while the way I am doing it is straightforward and works, it does not feel like the best way.
For example, I have a manager class, ie UserManager which has the following interface:
class UserManager
{
public IList<User> Users { get; ...}
public AddUser(...)
public RemoveUser(...)
}
So Adduser
and RemoveUser
should control the list, with the Users
collection as an output. I am using this collection in a binding, ie:
listBindingSource.DataSource = userManager.Users;
I am then manipulating the list via the binding, ie
listBindingSource.Add(new User(...))
This works, of course, but I am completely bypassing the UserManager
and the AddUser
/RemoveUser
functions in there! This of course seems very wrong. What is the correct way to use databinding?
UserManager
is inside a lib so I do not want to put any binding objects in there, as I feel that should be a gui thing. On the other hand, with binding, my gui has taken complete control over my collection.
Best Answer
As your code stands now, you can't do what you're after. At some point, the collection has to support the
IBindingList
interface (which is what theBindingSource
object you have on the form does). If you want to make use of yourUserManager
class to do the manipulations, for practical purposes you'll have to change the internal data store for theUsers
property to use aBindingList<User>
(you should still be able to return it typed as anIList<User>
as you have now, just change the actual concrete implementation toBindingList<User>
). Doing this will expose theIBindingList
interface to the grid and it will detect changes that are made elsewhere, namely in yourUserManager
class.This will, however, only cause it to pick up on changes made to the list, not to individual elements contained in the list (in other words, additions and removals will be reflected on the UI, but modifications won't be). In order to accomplish this, you need to implement
IPropertyChanged
on theUser
class (assuming it doesn't already).