views:

520

answers:

2

OK so I want to subclass ObservableCollection to add a property to it. Unfortunately the PropertyChanged event is protected. Basically I want to subclass it to have a SelectedItem that I can bind to for lists in my MVVM WPF app.

Here's the skeleton of my class:

public class SelectableList<T> : ObservableCollection<T>
{
    public T SelectedItem {get;set;}
}

But I cannot do the following:

SelectableList<int> intList = new SelectableList<int>();
intList.PropertyChanged += new PropertyChangedEventHandler(intList_Changed);

because of access restrictions. This causes me to ask a deeper question. How come the UI can get notified of PropertyChanged events(e.g. Count property) and I can't do it in code-behind?

My head is spinning, can someone please enlighten me?

A: 
SelectableList<int> intList = new SelectableList<int>();
((INotifyPropertyChanged)intList).PropertyChanged += 
    new PropertyChangedEventHandler(intList_Changed);

ObservableCollection implements INotifyPropertyChanged explicitly. As to why this is done, I don't know. Binding doesn't deal with ObservableCollections, it deals with INPCs, INCCs, and DependencyProperties.

Will
A: 

The UI can and does get notified. This is a restriction JUST with ObservableCollection, which defines the PropertyChanged event as protected.

FWIW, I think you're better off leaving ObservableCollection alone and just adding another property to your VM.

micahtan