Wednesday, July 22, 2009

Binding to an ObservableCollection in a WPF ListBox

Bind your items control to an ObservableCollection of objects that implement INotifyPropertyChanged, and invoke PropertyChanged within the setter of each Property you want to see change in your UI.

the wrong way:
- declare private instance of ObservableCollection, and public getter that returns this instance
- Bind to Property (which is still null)
- Do work to get data (triggered by some event, like button click)
- set ObservableCollection to be new instance and populate with data.
- Wonder why no changes are propogating to UI


the right way:
- Instantiate private ObservableCollection in *Constructor* for ViewModel
- Bind to it (empty *but non-null* collection)
- Do work to get data (triggered by some event, like button click)
- populate (already instantiated and bound) Collection with data
- Bask in glory as UI fills with data goodness


obvious when you think about it...