Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access MVVM parent view model from within collection

Tags:

c#

.net

mvvm

wpf

alt text

The picture above illustrates my program. Arrows indicate Binding.

My MainWindow.xaml has its datacontext set as MainVM.

The Window has a tab control binded to a ObservableCollection of ViewModels. Using a data template, the tab control displays views corresponding to the ViewModel.

The ObservableCollection is found in MainVM.

How do I access properties found in MainVM from ViewModel (enclosed in the ObservableCollection)?

I am open to answers that are require modification of my programming model.

like image 378
Kiang Teng Avatar asked Jan 11 '11 17:01

Kiang Teng


3 Answers

Building on what Kent said . . .

From an architectural standpoint, your ViewModel class shouldn't need to know anything about MainVM. Anything that it needs to know should be passed in to the instance of ViewModel so that it can stay atomic, and not have to worry about things that call it. From a SOLID standpoint, this is the Dependency Inversion principle.

Whatever properties from MainVM need to be accessed within ViewModel should be passed as part of the construction of the instance of ViewModel. Personally, I'm a fan of including them in a constructor, but you could also expose them as properties.

An overkill method (which I don't recommend), is setting up your constructor to take an instance of MainVM, and passing in this in the constructor. e.g.:

public class ViewModel
{
    private readonly MainVM _parent;

    public MainVM Parent => _parent;

    public ViewModel(MainVM parent)
    {
          _parent = parent;
    }
 }

then when you create your ViewModel you can just:

 ViewModel vm = new ViewModel(this);
like image 68
Robaticus Avatar answered Nov 15 '22 16:11

Robaticus


Depending on how much interaction you need, you could kind of go the other way by firing events from the ViewModel class and having MainVM handle them and set properties on the individual ViewModel accordingly.

Another option would be when you instantiate the ViewModel Collection (which I assume is done in MainVM somewhere?), you could just pass in MainVM as a constructor parameter and keep and instance of MainVM inside of each ViewModel.

like image 4
Steve Danner Avatar answered Nov 15 '22 18:11

Steve Danner


Who creates instances of ViewModel? If there is a tight relationship between MainVM and ViewModel then perhaps ViewModel should take an instance of MainVM in its constructor.

The alternative is to come up with a different design that does not require ViewModel to have access to the MainVM. Doing so would require more information (and a separate question).

like image 2
Kent Boogaart Avatar answered Nov 15 '22 16:11

Kent Boogaart