Goran
Goran

Reputation: 6528

When should we reference a ViewModel from another ViewModel

In many ViewModels I will need a collection from another ViewModel. Basically each VIewModel has a List property which is of type ObservableCollection. and most of the time ViewA needs VIewModelA (for CRUD) and ViewModelB.List (for read-only purpose).

What is the recommended approach here?

  1. inject a ViewModelB into ViewModelA and expose a EntityBList property
  2. add/copy the same GetList procedure in ViewModelA from ViewModelB?
  3. in ViewA xaml reference both ViewModelA and viewModelB

Upvotes: 0

Views: 426

Answers (2)

Derek Beattie
Derek Beattie

Reputation: 9478

I generally use option 1. Injecting a SharedViewModel singleton into view models that need the data works well. It's also easy to add additional shared data when needed.

Upvotes: 0

benjgorman
benjgorman

Reputation: 722

1) Not sure about this one.

2) If you are duplicating code there is generally a better solution.

You could make use of the singleton pattern and have one class which holds your Collections. Then each Viewmodel is accessing the same list. Call it DataAccessor or something similar.

3) I wouldn't have a view reference two different Viewmodels. Why not just merge Viewmodel A and B? Why are they currently separate if they both deal with ViewA?

Upvotes: 0

Related Questions