2012-12-06 29 views
12

我試圖創建一個應用程序使用MVVM模式與嵌套viewmodels。主視圖模型是包含三個UserControl的ShellView,每個UserControl都有自己的視圖模型。該ShellView視圖模型在創建代碼隱藏,像這樣:將UserControl的datacontext設置爲父視圖模型中定義的ViewModel

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

現在,我的ShellViewModel包含了其他的ViewModels爲屬性:

public CustomerViewModel CustomerViewModel { get; set; } 

    public ContactsViewModel ContactsViewModel { get; set; } 

如何訪問從用戶控件的XAML這些屬性呢?我希望能夠做到這樣的事情:

DataContext="<<ParentWindowViewModel>.CustomerViewModel> 

我該如何做到這一點?我已經嘗試過:

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

但調試說「型‘對象’的數據上下文無法解析屬性‘CustomerViewModel’任何幫助,將不勝感激

回答

13

您只需使用

DataContext="{Binding CustomerViewModel}" 

您已經在您的構造函數中設置了DataContext = _shellViewModel;,因此將整個窗口的datacontext設置爲ShellViewModel,所以當您定義一個綁定時,它會查找您定義的datacontext中的路徑,這就是爲什麼上述綁定將請在您的ShellViewModel實例上尋找CustomerViewModel屬性。

相關問題