INotifyCollectionChanged is not updating the UI

Vikram picture Vikram · Apr 30, 2013 · Viewed 13.9k times · Source

I have a class as shown below. All the functions I have removed for brevity

public class PersonCollection:IList<Person>
{}

Now I have one more Model class as shown below. AddValueCommand is class deriving from ICommand which again I am omiting.

public class DataContextClass:INotifyCollectionChanged
{
    private PersonCollection personCollection = PersonCollection.GetInstance();

    public IList<Person> ListOfPerson
    {
        get 
        {
            return personCollection;
        }            
    }

    public void AddPerson(Person person)
    {
        personCollection.Add(person);
        OnCollectionChanged(NotifyCollectionChangedAction.Reset);
    }


    public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { };
    public void OnCollectionChanged(NotifyCollectionChangedAction action)
    {
        if (CollectionChanged != null)
        {
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));
        }
    }       

    ICommand addValueCommand;

    public ICommand AddValueCommand
    {
        get
        {
            if (addValueCommand == null)
            {
                addValueCommand = new AddValueCommand(p => this.AddPerson(new Person { Name = "Ashish"}));
            }
            return addValueCommand;               
        }
    }
}

In the main window I am binding my UI to Model as shown below

 DataContextClass contextclass = new DataContextClass();           
 this.DataContext = new DataContextClass();

And My UI looks like as shown below

<ListBox Margin="5,39,308,113" ItemsSource="{Binding Path=ListOfPerson}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBox Height="20" Text="{Binding Path=Name}"></TextBox>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button Content="Button"  HorizontalAlignment="Left" Command="{Binding Path=AddValueCommand}" Margin="233,39,0,73" />

My List Box is not updating with the new value when button is clicked. What I am missing here.

Answer

Daniel Hilgarth picture Daniel Hilgarth · Apr 30, 2013

INotifyCollectionChanged has to be implemented by a collection class. Not by the class containing the collection.
You need to remove INotifyPropertyChanged from DataContextClass and add it to PersonCollection.