简体   繁体   中英

Deal with collections in model in WPF MVVM

I've started to learn WPF\\MVVM approach and get bit confused. I've:

class ModelAAA {
    public List<Foo> Foos{get; protected set;}
    //..

    public void Boo()
    {
       //Some complex logic updating Foos
    }
}

class ViewModelAAA{

    private ModelAAA _modelAAA

    public ObservableCollection<Foo> Foos{get; protected set;}

    public void ViewModelAAA(ModelAAA modelAAA)
    {
        this._modelAAA = modelAAA;
        this.Foos = new ObservableCollection(modelAAA.Foos)
    }

    public void Boo()
    {
       this._modelAAA.Boo();
       //What should I do here?
    }
}

So if I use Boo method of view model, what is proper view to update collection in ViewModel. I've got few ideas, but they all seems to by ugly. Should I manauly recreate\\change viewModel Foos each time? As I understad ObservableCollection is not wrapper like object.

PS I'm want to make it whitout using ObservableCollection in model

No, you do not need manually change it, as this is ObservableCollection , but you are changing original collection and not observable one.

To notify listeners of your Observable you need to act on Observable itself.

Example:

public void Boo()
{
   this.Foos.Boo();

}

Your Model does not need to use ObservableCollection , but has to notify your ViewModel that something changed in the Collection.

this creates a copy of your List, which is indeed observable, but is not changed at all after that:

this.Foos = new ObservableCollection(modelAAA.Foos);

I would not recommend to create a new ObservableCollection, each time the Model-Collection changed. Instead implement the INotifyCollectionChanged in your Model-Collection and handle the events in your Viewmodel properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM