Sturm
Sturm

Reputation: 4125

Is INotifyPropertyChanged needed for binding ObservableCollection?

When I'm binding, say a Label to a string, I define the string this way:

private string _lbl;
public string Lbl
    {
     get
     {
          return = _lbl;
     }
      set
     {
         _lbl=value;
          OnPropertyChanged("Lbl");
     }
}

With the INotifyPropertyChanged interface implemented in my class.

Should I define the same way an ObservableCollection or I just could leave it this way?

public ObservableCollection<File> myFiles {get; set;}

Upvotes: 0

Views: 844

Answers (2)

Fede
Fede

Reputation: 44068

As a general rule, I tend to define ObservableCollections like this:

    private ObservableCollection<Item> _items;
    public ObservableCollection<Item> Items
    {
        get { return _items ?? (_items = new ObservableCollection<Item>()); }
    }

This is called "Lazy initialization", where the ObservableCollection is only instantiated where it is first accessed.

This is a good way to ensure your Collection Will Never Be Null

Notice that it does not have a setter, because an ObservableCollection is not something that you usually assign to. Instead, if you want to completely replace items, do:

Items.Clear();
//... Add all the new items

This avoids WPF having to rebind all the CollectionChanged events and stuff in order to listen to and react to items added / removed from the collection. You only have 1 instance of the collection, forever. Whatever items you place on it, the collection remains the same.

This is not to be confused with the PropertyChange notification inside the ITEMS of the collection. WPF handles these concepts separately, because property changes are notified by ITEMS, but Collection changes (Item added or removed) are notified by the Collection itself.

Upvotes: 5

Michael Gunter
Michael Gunter

Reputation: 12811

If the myFiles property can change, then yes, you should raise the PropertyChanged event. If not (that is, if it's got no setter, or it has a private setter that is only set once, e.g. in the constructor), then you don't need to raise the event. The collection itself will raise its own PropertyChanged and CollectionChanged events, but the object that contains the collection must raise PropertyChanged if the property that contains the collection changes.

Upvotes: 1

Related Questions