The relationship between parent and child views through the notifychanged or command?

In my WPF application, I follow the MMV pattern. I have a main view with nested child views. I have a main virtual machine that contains instances of child virtual machines. At some point, the main virtual machine should be informed when certain properties of the child virtual machine change.

I searched a lot on the Internet. The preferred approach seems to be to use the existing structure (MVVMlight / Prism) and / or some kind of messaging service. Whenever a question is asked about interacting with a VM, you can be sure that at least one answer involves using this approach. Although I see very well the benefits of this in a large application (or if you are looking for a “one-stop” solution), sometimes for small applications sometimes there is a lot of overhead.

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

  • Subscribe to a child VM NotifyPropertyChanged.

OR

  • has a main VM command (Relay) for the child VM, so the child VM can execute the command whenever a certain property changes (possibly even passing the changed value as a command parameter), so the main VM knows about the change and can handle it .

I am wondering if there is something “wrong” with these two approaches at all, because I don’t see them breaking the MVVM rules? Maybe I missed something?

Can one of these approaches be used if you cannot take advantage of using the message-based approach in the application?

+4
source share
3 answers

, , . - "" .

- vms, (Relay) , ( , , brrr...), , , . , , - , , :).

- , ( master-child vms), , , . / , . , , , (, ?) , , , , - :). , :)

+2

. viewmodels, Action Func contructor. , .

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();
            }
        }
    }
}
+1

, , . , , .

  • , INotifyPropertyChanged, . , , , .

  • , , , , .

  • , , , . , datacontext.

0
source

All Articles