hasdrubal
hasdrubal

Reputation: 1148

c# wrap model object containing list for MVVM binding

Lets say I have a model object

class ModelClass
{
    public List<Element> eList;

    public void MethodA()
    {
        doSomething();
    }
}

I would like to use this object in an MVVM as well. The Viewmodel would then invoke methods like MethodA to manipulate the data and the elements in eList would be updated. Is there a way to do this without making eList an ObservableCollection? I'd like to do so in order to use this ModelClass in other places as well without too much code polution.

Upvotes: 1

Views: 242

Answers (1)

Nhan Phan
Nhan Phan

Reputation: 1302

If we compare List and ObservableCollection then both are implemented from IList. There isn't much of a difference there. The most difference is ObservableCollection also implements INotifyCollectionChanged interface, which allows WPF to bind to it.

Therefore, if you don't want to use List instead of ObservableCollection in your model class then you need to implement the class with INotifyCollectionChanged:

class ModelClass:INotifyCollectionChanged
{
    public List<Element> eList;// call OnCollectionChanged() when you set/add/remove...the list).

    public void MethodA()
    {
        doSomething();
    }

    #region INotifyCollectionChanged Members

    protected void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (CollectionChanged != null)
            CollectionChanged(this, e);
    }

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    #endregion

}

Upvotes: 1

Related Questions