Im new to MVVM and have small problem. I have two user controls: parent and child(with view, viewmodel, model classes). And need to pass some properties from parent to child. For now ive managed it by writing such code:
public static readonly DependencyProperty CallbackActionProperty =
DependencyProperty.Register("CallbackAction", typeof (Action),
typeof (ChildView), new PropertyMetadata(default(Action)));
public Action CallbackAction
{
get { return (Action) GetValue(CallbackActionProperty); }
set
{
SetValue(CallbackActionProperty, value);
((ChildViewModel)this.DataContext).CallbackAction = value; // Change ViewModel property too
}
}
This is dependency property in ChildView and on its set i also set its ViewModel‘s property. After that i access that dependency property from ParentView and set the CallbackAction-> that sets the CallbackAction in Child’s ViewModel.
Code:
this.Loaded += (sender, args) => childUc.CallbackAction = ((ParentViewModel) this.DataContext).RefreshStatuses;
childUc is usercontrol, located on parent and represented by ChildView.
Code is ugly, so i hope to see better practice in terms of not breaking pattern.
Thank you.
Yep – this code is pretty ugly. In fact I am struggling to work out exactly what it does!
One of the main tenants of the MVVM pattern is that the ViewModel should be unit testable and it should be possible to execute it without the view. When faced with this kind of problem, think about the view Model alone and ignore the view.
Your ParentViewModel has a reference to the ChildViewModel, you can make this a two way relationship by having the ParentViewModel provide a reference to itself when you create the ChildViewModel. This means that from the ChildViewModel you can execute any public method on the ParentViewModel.
With this in mind, you should be able to solve your problem!
(Also, you should not add logic in your dependency property getter or setter, this code may or may not be called depending on how your dependency property value is set.)