Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting datacontext of UserControl to ViewModel defined in parent viewmodel

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.

like image 464
ZymLink Avatar asked Dec 06 '12 09:12

ZymLink


1 Answers

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.

like image 117
Adi Lester Avatar answered Oct 02 '22 17:10

Adi Lester