should I store a reference to the parent viewmodel in the child viewmodel?

.net, c#, mvvm, wpf

Solution

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

Problem

So if I store the parent ViewModel's reference in the child ViewModel will that be a crime ? Will I break MVVM rules ? My child view is a Window with a context menu. When the appropriate menu item is selected a new child view needs to be created. The parent only is responsible to create the child view. So keeping a reference to the parent view model, will do lot of good for me. At the same time I do not want to break the pattern 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; } } ```

Original source