views:

45

answers:

3

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 child 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!

+1  A: 

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.

AlvinfromDiaspar
Confirmed that this works as a possible solution.
AlvinfromDiaspar
A: 

The child view inherits its DataContext from its parent view, there is no need to declare or assign it a second time.

Ozan
Sorry, it is not a real child of its parent. I should say that it is a sub-view (i.e. A view that is created/owned by its parent-view). There is no inheritance here.
AlvinfromDiaspar
+1  A: 

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;
    }
}
Jeremy Likness