Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

mvvm

wpf

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;
    }
}
like image 255
aalimian Avatar asked Mar 14 '13 21:03

aalimian


3 Answers

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.

like image 189
Ibrahim Najjar Avatar answered Sep 30 '22 06:09

Ibrahim Najjar


The answer is no, but for your purpose, why do you need this reference if all the parent is doing is creating the child viewmodel. What is the purpose of having that linkage?

like image 22
TYY Avatar answered Sep 30 '22 06:09

TYY


While this pattern is not at all a crime or "code smell", it may in many situations work better to pass a reference to the parent in the form of an implementer of an interface, rather than as its own class. Thus, only the properties or methods the child needs to access in the parent are defined in the interface, but the child isn't given access to other public methods or properties of the parent class, which could cause bugs if used by mistake. This may involve a bit more code, but the looser connection between classes may offer benefits. If nothing more, it helps make the connection between child and parent more self-documenting and easier for people reading the code to understand.

like image 28
Wayne VanWeerthuizen Avatar answered Sep 30 '22 05:09

Wayne VanWeerthuizen