Access MVVM parent view model from within collection
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 ViewModel
s. 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.
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);
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
.
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).
精彩评论