Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between parent and child viewmodel via notifychanged or command property?

Tags:

c#

mvvm

wpf

In my WPF application I'm following the MMV pattern. I have a main View with nested child Views. I have a main VM that holds instances of the child VMs. At some point, the main VM needs to be informed when certain properties of the child VM change.

I have searched the Web a lot. The prefered approach seems to be to use an existing framework (MVVMlight/Prism) and/or some sort of messenger service. Whenever a question dealing with VM-interaction is asked on any board/faq, you can be sure at least one answer suggests using this approach. While I can very well see the advantages of it in a big application (or if you are looking for a "universal" solution), it sometimes seems to be a lot of overhead for small applications.

To me, the most obvious approaches, especially in small applications, would be to

  • subscribe to the child VM's NotifyPropertyChanged.

OR

  • have the main VM pass a (Relay)Command to the child VM, so that the child VM can execute the command whenever a certain property changes (maybe even passing the changed value as command parameter), that way the main VM knows about the change and can deal with it.

I am wondering if there is something "wrong" with those two approaches in general, for I cannot see them violating MVVM rules? Maybe I am missing something?

Is it ok to use one of these approaches when you can't make use of the advantages of using the messenger based approach in an application?

like image 834
sth_Weird Avatar asked Jun 30 '16 09:06

sth_Weird


1 Answers

We use a simple approach for this. When you create this child viewmodels just pass an Action or Func into the contructor. Then invoke that action anytime you need to update the parent view model.

Example

public class ParentViewModel
{
    public ParentViewModel()
    {
        childViewModel = new ChildViewModel(MyAction);
    }

    private void MyAction()
    {
        //i was called by childview model, now do something
    }

    ChildViewModel childViewModel;
}

public class ChildViewModel
{
    private readonly Action action;

    public ChildViewModel(Action action)
    {
        this.action = action;
    }

    private int myVar;

    public int MyProperty
    {
        get { return myVar; }
        set
        {
            myVar = value;
            if (something)
            {
                //call the parent viewmodel
                action.Invoke();
            }
        }
    }
}
like image 96
adminSoftDK Avatar answered Oct 02 '22 14:10

adminSoftDK