views:

264

answers:

1

I am binding an object(named Client) with and ObservableCollection(named Contacts) property to my Silverlight view. My Client class has a few string properties on is and the ObservalbeCollection called Contacts. There is a property on my viewmodel named Client(Which implements INotifyPropertyChanged) that contains the Client object. If I bind the ListBox in my view to the ObervableCollection on the object like this:

ItemsSource="{Binding Path=Client.Contacts, Mode=TwoWay}"

and add an Contact item to the collection, the view updates properly and I am shown my newly added Contact. This all works great.

If I create a Contacts property on my ViewModel like this public ObservableCollection Contacts { get { return Client.Contacts; } and bind the ListBox to

ItemsSource="{Binding Path=Contacts, Mode=TwoWay}"

the view is never updated.

I add the Contact item to the Client like this:

Client.Contacts.Add(newContact)

Why doesn't the ListBox of Contacts update? How can I change this so it does? Is the Client.Contacts binding OK to use? Putting a break in the code after adding the new Contact shows that new new Contact object is getting added to the collection but the view is not seeing the addition.

A: 

It looks like when the binding havent executed when execution reached ItemsSource="{Binding Path=Contacts, Mode=TwoWay}". Can you verify whether you instantiating the collection in the constructor of the ViewModel, because I feel at the binding time the Contacts instance not set(null)

Jobi Joy
I worked out the problem I was having. When adding the item to the collection like this:Client.Contacts.Add(newContact)The binding is never notifed of the change to the underlying property. So, to let the binding know that I have updated one of it's properties, I fired the PropertyChanged event for the Contact property and now the binding is notified. In my case the ItemsSource can be bound to the Contacts property and respond to changes.Thanks for your help!
DaveB
But I see a performance hit in that solution you described.. For every collection addition/removal you are firing a propertychanged event which cause the entire ItemsControl to rebuild its Item visuals-I think that is a bad idea. Rather the typical way is raising INotifyCollectionChanged(Which is inbuilt in to the ObservableCollection) and let the ItemsControl build only relevant Visual for the item instead of recreating everything.
Jobi Joy
Would using a backing variable for the collection and adding and removing items from it still cause the propertychanged event to fire?
DaveB
I don't think the swapping of collection is worth for the effort and will surely affect the performance. So let the Client class constructor has a collection instance and Contacts property be a readonly property is the idle way to do this. You can always have DataTemplate elements having TwoWayBind to reflect your new values.
Jobi Joy