Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose a Model's collection in the ViewModel

Tags:

c#

mvvm

wpf

I'm implementing MVVM for a class which represents recursively nested types. For example:

class NestedType
{
    // Other properties here

    public Collection<NestedType> SubElements {get; set;}
}

class NestedTypeViewModel
{
    ObservableCollection<NestedType> ModelCollection { ??? }
}

How do I expose the items in the Model's collection in an observable way? (i.e., the View will be adding, creating, and modifying the subelements) I assume I need the collection in the ViewModel to be ObservableCollection<T> but what about in the Model? I could also make that an ObservableCollection and just directly expose it...

Any suggestions?

like image 716
Brian Triplett Avatar asked Nov 05 '22 16:11

Brian Triplett


1 Answers

You can directly return the ObservableList from your model. WPF will take the reference of the Collection and registers to the CollectionChanged Event of the model collection.

class MyViewModel
{
  public ObservableCollection<NestedType> MyItems { return Model.Items; }
} 

BUT, you will break what you are trying to achieve by using MVVM. A ViewModel should not expose a model, single or collection, otherwise your view could bind to a model which you should not do in MVVM.

Well MVVM is no religion and everyone implements certain parts differently. If this is no problem for you ... Go ahead and do it directly.

If you want a clean solution, you have multiple options to go from here. Just allowing a Manager to modify the collection of the model and create a corresponding view model or My favorit approach is to have an object that syncs model and viewmodel collection, by automatically wrap newly added models in a new view model and add this vm into the parent viewmodel list.

like image 138
dowhilefor Avatar answered Nov 14 '22 23:11

dowhilefor