Setting datacontext of UserControl to ViewModel defined in parent viewmodel

ZymLink picture ZymLink · Dec 6, 2012 · Viewed 24.9k times · Source

I'm trying to create an application using the MVVM pattern with nested viewmodels. The master viewmodel is ShellView which contains three UserControls, each with their own viewmodel. The ShellView ViewModel is created in code-behind like so:

public ShellView()
{
    InitializeComponent();
    _shellViewModel = new ShellViewModel();
    DataContext = _shellViewModel;
}

Now, my ShellViewModel contains the other ViewModels as properties:

    public CustomerViewModel CustomerViewModel { get; set; }

    public ContactsViewModel ContactsViewModel { get; set; }

How do I access these properties from the XAML of the UserControls? I would like to be able to do something like:

DataContext="<<ParentWindowViewModel>.CustomerViewModel>

How can i accomplish this? I already tried:

DataContext="{Binding DataContext.CustomerViewModel, RelativeSource={RelativeSource FindAncestor, AncestorType=Window, AncestorLevel=1}, Path=DataContext.CustomerViewModel}">

but the debugger says "Cannot resolve property 'CustomerViewModel' in data context of type 'object'. Any help would be appreciated.

Answer

Adi Lester picture Adi Lester · Dec 6, 2012

You simply need to use

DataContext="{Binding CustomerViewModel}"

You've already set DataContext = _shellViewModel; in your constructor, so that sets the datacontext of the entire window to ShellViewModel, so when you define a binding, it looks for the path in the datacontext that you have defined. That's why the above binding will look for the CustomerViewModel property on your ShellViewModel instance.