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
OR
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?
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();
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With