user2612602
user2612602

Reputation: 31

Binding ObservableCollection

How to solve problem of changing collection content?

One approach is to clear collection and using foreach loop add new content. Collection must change in runtime and because sometimes I have half a million elements to add, It's take too long and not acceptable to me.

When try _myObservableCollection = new ObservableCollection<T>(_anotherCollection); binding to view is broken (referencing old collection)

Is it possible to solve this problem an how?

Upvotes: 1

Views: 118

Answers (1)

nvoigt
nvoigt

Reputation: 77285

If your binding to the view is broken after assigning the new collection, you should properly implement INotifyPropertyChanged for the property of your collection.

Edit: example

// implement the interface on your viewmodel
public class ExampleViewModel : INotifyPropertyChanged
{        
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private ObservableCollection<UIElement> collectionBackingField;

    public  ObservableCollection<UIElement> Collection
    {
        get { return collectionBackingField; }
        set
        {
           if(value != collectionBackingField)
           {
              collectionBackingField = value;

              // call the method that notifies all observers of the changes
              NotifyPropertyChanged();
           }
        }
    }
 }

Please note that now all changes that the UI needs to know about must be through the property. No setting the private backing field manually from anywhere in code.

Upvotes: 2

Related Questions