Should I keep a link to the parent view model in child view?

So, if I save the parent link of the ViewModel in the child view of the ViewModel, would that be a crime? Am I breaking the rules of MVVM? My child view is a window with a context menu. When the corresponding menu item is selected, it is necessary to create a new child view. Only the parent is responsible for creating the child view. Therefore, keeping a reference to the parent view model will do me a lot of good. At the same time, I do not want to break template rules.

class MainViewModel { List<ChildViewModel> _childrenViewModels = new List<ChildViewModel>(); public AddChild(ChildViewModel childViewModel) { _childrenViewModels.Add(childViewModel); childViewModel.Owner = this; } } class ChildViewModel { private Child _child; public MainViewModel Owner { get; set; } public ChildViewModel(Child child) { _child = child; } } 
+6
source share
3 answers

NO. In general, if you use this technique, trying to hide it behind an abstraction many times, in fact this is what the famous Caliburn.Micro [I like] project runs the IChild interface .

+3
source

The answer is no, but for your purpose, why do you need this link, if the whole parent does, creates a child view model. What is the purpose of this connection?

+2
source

Although this template is not at all a crime or a β€œcode smell”, in many situations it is better to work with passing a reference to the parent in the form of an interface implementation, rather than as your own class. Thus, only the properties or methods that the child should receive in the parent are defined in the interface, but the child is not granted access to other public methods or properties of the parent class, which can lead to errors if they are used by mistake. This may include a bit more code, but a weaker connection between classes can be beneficial. If nothing more, it helps make the bond between the child and the parent more self-documenting and easier for people reading the code to understand.

0
source

All Articles