I have a parent View that is xaml-binded to a ViewModel (the viewmodel is declared in the xaml).
This parent view can then display a child View (via NavigationService, aka navigation:Frame).
The parent view never goes out of scope, but I want the new c开发者_运维知识库hild View to share the parent's ViewModel.
How can i do this? Because by declaring the same viewmodel in the child View's xaml would mean the child view gets it's own viewmodel instance (i.e. it is not the same viewmodel instance as it's parent view).
Thanks!
Sounds like a perfect opportunity to either (a) use MEF. Export the view model, then import it in both the parent and child views. By default, they will share the same object. Or (b) create a locator class that keeps track of the view model instances, exposed via a static property, and use that static property to retrieve the view model in the parent and the child:
public static class Locator
{
private static readonly MyViewModel _instance = new MyViewModel();
public static MyViewModel Instance
{
get { return _instance; }
}
}
public partial class MyView
{
public MyView()
{
InitializeComponent();
LayoutRoot.DataContext = Locator.Instance;
}
}
Well until somebody gives me a good answer i'll be using the following solution (if it works as I havent really tested it yet).
My hack solution:
The ViewModel will have a public static reference to itself. Then child view(s) will set its DataContext to the ViewModel's static reference.
Cheers.
The child view inherits its DataContext from its parent view, there is no need to declare or assign it a second time.
精彩评论