Reputation: 6132
I have an application which shows some ListBox's. These ListBox's are bound to data. One of the lists is a list of Doors, while the other list is a list of Users.
The list of Doors are coming from a DataManager class which communicates with the database. The list of Users is coming from an other class which does some calculations.
I've bound the two ListBox's to their appropiate ObservableList getter setter.
For the door:
public ObservableList<Door> Doors
{
get { return DataManager.Doors; }
}
and for the user:
public ObservableList<User> Users
{
get { return classLogic._users; }
}
Here comes the problem. When I add or remove a Door, the list on the UI gets updated. When I add or remove a User, the list doesn't get updated. I have to reload the view (restart the application) to update it. What am I missing? Why isn't it working?
Upvotes: 2
Views: 143
Reputation: 6132
I've found out myself that there are three steps to complete. I don't believe a PropertyChanged event is needed to update the ListBox. This may be since .NET 4.0 because I've read in versions below, the databinding isn't really correct yet.
The first step is that the list has to be a private static ObservableList<...>
. The second is that the getter of this list has to be the appropiate type as well. This means in my case, the following code needs to be in ClassLogic:
private static readonly ObservableList<User> _users= new ObservableList<User>();
public static ObservableList<User> Users
{
get { return _users; }
}
And the third thing is, when calling this function (getter) in the DataContext class to bind the data to the ListBox, the classname has to be used instead of an instance of that class!
So, in this case it would be:
/// <summary>
/// Gets the Users that are managed by the ClassLogic class
/// </summary>
public ObservableList<User> Users
{
get { return ClassLogic.Users; }
//wrong would be:
//get { return classLogic.Users }
}
These 3 steps bound my data and made sure the ListBox updated when the contents of the list was updated as well.
Upvotes: 1
Reputation: 12533
an observable collection raises PropertyChanged for properties of each item
like if you had a IsDoorClosed Property it would update
removing an element raises a CollectionChanged event on Doors but the UI is not updated since a PropertyChanged event was not Raised on the Bound Property Doors .
you need to Raise A PropertyChanged event on Doors on each CollectionChanged of Doors .
something along the lines of : this is psado code , it was written here for as an example for your benefit , so check for any syntax errors .
Doors.CollectionChanged += OnDoorsCollectionChanged;
private static void OnDoorsCollectionChanged(object sender , CollectionChangedEventArgs e)
{
PropertyChanged(sender,new PropertyChangedEventArgs("Doors"));
}
Upvotes: 2