Setting datacontext of UserControl to ViewModel defined in parent viewmodel

25,061

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.

Share:
25,061
ZymLink
Author by

ZymLink

I'm currently a student at the Engineering College of Aarhus, where I study Information- and Communication Technology Engineering (Nerd for short).. I expect to graduate in the summer 2013, and hope to get a job in the areas of defence or healthcare.

Updated on July 28, 2020

Comments

  • ZymLink
    ZymLink almost 4 years

    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.