Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection loses binding when I "new" it

Tags:

c#

binding

wpf

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?

like image 862
TomDestry Avatar asked Feb 09 '13 00:02

TomDestry


3 Answers

Make sure you are raising a PropertyChangedEvent after you reintialize your collection. Raising this event will allow the view to handle changes to the property with the model having no knowledge of the view.

class Model : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    private ObservableCollection<string> _list = new ObservableCollection<string>();
    public ObservableCollection<string> List
    {
        get { return _list; }
        set 
        { 
            _list = value;
            NotifyPropertyChanged("List");
        }
    }

    public Model()
    {
        List.Add("why");
        List.Add("not");
        List.Add("these?");
    }
}
like image 162
Ryan Byrne Avatar answered Oct 24 '22 20:10

Ryan Byrne


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");
        }
    }
}
like image 5
RayB64 Avatar answered Oct 24 '22 21:10

RayB64


Supposing you've implemented INotifyPropertyChanged on your ViewModel, you can raise the property changed event on your ObservableCollection whenever you assign a new value to it.

public ObservableCollection<string> MyList { get; set; }

public void SomeMethod()
{
    MyList = new ObservableCollection<string>();
    RaisePropertyChanged("MyList");
}
like image 4
Joao Avatar answered Oct 24 '22 22:10

Joao