views:

2031

answers:

3

I have a List<Foo> from a non-WPF assembly which I'm attempting to databind to a WPF <ListBox>. Initially, the list items display correctly, but when I add a new item to the List<Foo>, the listbox doesn't add a list item. How do I tell the list box to re-bind / update / refresh the data and show the new item?

(n.b. complete WPF n00b)

+4  A: 

You should use a ObservableCollection instead, then you'll get updates automatically.

Scott
Can I use an ObservableCollection in a non-WPF assembly?
harriyott
Yes, if you include PresentationBase (I think, the class is in System.Collections.ObjectModel, but the impl is in PresetationBase); or if you want to get the same functionality make your own ObservableCollection by implementing INotifyCollectionChanged.
Scott
It's in WindowsBase, and I agree. There's usually no reason to expose anything other than ICollection<T> or IList<T>, so you can always swap out the implementation later.
Kent Boogaart
+3  A: 

Although using an ObservableCollection is the best way, to answer the actual question, the way to update manually is to call BindingExpression.UpdateTarget

harriyott
Did you try this in the scenario of the question? The reason I ask is that I was under the impression that UpdateTarget will not update the list if the collection is the same reference (if you create a new collection then this would force a rebind, or if you set the source to null first).
Scott
+2  A: 

Thanks for posting this answer. Even if you use ObservableCollection, you may need to use BindingExpression.UpdateTarget. This can be the case if the collection is not in the UI thread. I've been writing some multi-threaded WPF apps, and I've been finding myself having to strip out data binding when I move model code to another thread, because I can't count on the update system to really work. While I find data binding to be a great concept, I think the opaqueness of the data binding system has been a real hindrance for my adoption of it. (Sorry for the rant!) Thanks again, Adam.