Reply to comment

Do not use ObservableCollection<T>

Update Controls not only implements INotifyPropertyChanged for you, it also makes all of your collections observable. When you use Update Controls, you should not also use ObservableCollection<T>. Use a regular List<T> instead.

Define a property of type List<T> in your data model. Select this property and hit Ctrl+D, G. This code will be generated for you:

public class ContactList
{
    private List<Person> _people = new List<Person>();

    #region Independent properties
    // Generated by Update Controls --------------------------------
    private Independent _indPeople = new Independent();

    public Person NewPerson()
    {
        _indPeople.OnSet();
        Person person = new Person();
        _people.Add(person);
        return person;
    }

    public void DeletePerson(Person person)
    {
        _indPeople.OnSet();
        _people.Remove(person);
    }

    public IEnumerable<Person> People
    {
        get { _indPeople.OnGet(); return _people; }
    }
    // End generated code --------------------------------
    #endregion
}

The Independent property is notified every time the collection changes (NewPerson and DeletePerson). It is also notified every time the collection is modified (the People getter). This is all happening in the data model.

The view model does not store a list. It only has a reference to the data model. Using this reference, it generates a collection of view models on the fly.

public IEnumerable<PersonViewModel> People
{
    get
    {
        return _contactList.People
            .Select(p => PersonViewModel.Wrap(p, _contactList));
    }
}

Where PersonViewModel.Wrap looks like this:

public static PersonViewModel Wrap(Person person, ContactList contactList)
{
    if (person == null)
        return null;
    else
        return new PersonViewModel(person, contactList);
}

This is much easier than managing ObservableCollections. You don't need an intermediate collection. You just wrap your data objects in a view model on the fly.

For more information, please see the example of using Linq to replace ObservableCollection<T>.

Reply

By submitting this form, you accept the Mollom privacy policy.