Alex Rivera | Logout

ObservableCollection loses binding when I "new" it

Asked 2013-02-09T00:56:30.390
17

I have a ListBox on my UI that is bound to a property of ObservableCollection. I set a new instance of the ObservableCollection into the property in the view model's constructor and I can add items to it with a button on the form. These are visible in the list.

All is good.

However, if I reinitialize the property with new in the button callback, it breaks the binding and the UI no longer shows what is in the collection.

I assumed the binding would continue to look up the values of the property, but its presumably linked to a reference which is destroyed by the new.

Have I got this right? Can anyone expand on how this is linked up? Is there a way to rebind it when my view model has no knowledge of the view?

Edit
Report

1 Answer

5

I think based on your description that what you need to do is refactor the property that exposes your ObservableCollection so that it raises a PropertyChanged event also when it is assigned a new value. Example:

public ObservableCollection<int> Integers
{
    get { return this.integers; }
    set {
        if (this.integers != value)
        {
            this.integers = value;
            RaisePropertyChanged("Integers");
        }
    }
}
answered 2013-02-09T01:06:23.577

Your Answer